Home > Blockchain >  JSON Tree structure with the key Folder on each level
JSON Tree structure with the key Folder on each level

Time:02-08

I will make requests to an API that have a folder structure.

Some request may respons with one level, others with 20 levels but I don't want this ugly structure.

Is there any good explanation for doing this recursive without knowing level depth?

for parent_folder in server_folders['folders']:
    print(parent_folder['name']   ' (PARENT)')

    for children in parent_folder['folders']:
        print("- "   children['name'])

        for sub_children in children['folders']:
            print("- - "   sub_children['name'])

            for sub_sub_children in sub_children['folders']:
                print("- - - "   sub_sub_children['name'])

                for sub_sub_sub_children in sub_sub_children['folders']:
                    print("- - - "   sub_sub_sub_children['name'])

CodePudding user response:

I'd solve this with recursion.

So by creating a method, called nested_list_print, with two parameters, the nested list that you are looping through, and how deep you want the depth to be.

like so:


def nested_list_print(init_folder, init_depth, depth=0):
    for i in init_folder:
        print('-'*depth   i)
        if depth > 0:
            nested_list(i, init_depth-1, depth 1)        

Now you can call the method with a depth of ex. 3 like this: nested_list_print(input_list, 3).

CodePudding user response:

Thanks Asger, smart!

I did end up with this rewrite of you excellent job!

def nested_list_print(init_folder, init_depth):
for i in init_folder['folders']:
    print('- '*(init_depth)   i['name'])
    if 'folders' in i:
        nested_list_print(i, init_depth 1)


nested_list_print(jsonfeed_w_folders, 0)
  •  Tags:  
  • Related