Why is my json file not nesting according to my depth parameter?

65 Views Asked by At

I am doing a small code to fetch files in a folder and get the path into a json.

def main(directory_path):
    submodules, depth = parse_directory(directory_path)
    output = {
        "name": os.path.basename(directory_path),
        "repository": os.path.dirname(os.path.realpath(directory_path)),
        "submodules": submodules
    }
    for i in range(len(submodules)):
        with open("output.json", "w") as output_file:
            json.dump(output, output_file, indent=depth[i]*4)

NB: parse_directory is an other function I made to locate the file in the folder. It returns submodules, a list of parameters, and depth, a list of steps my parse does to go fetch the file.

i.e: 'path/to/file' is 3 steps, 'path/file' is 2 steps.

So I tried to do a for loop but my indent are always the same even thought my values in depth are changing according to the deep of the file in the folder. As you can see in the following example, indent is not recursive.

{
        "project": "the lion king",
        "repository": "C:\\Users\\path\\to\\folder",
        "submodules": [
                {
                        "name": "mufasa",
                        "path": "example\\mufasa",
                },
                {
                        "name": "simba",
                        "path": "example\\mufasa\\simba",
                },
                {
                        "name": "nala",
                        "path": "example\\nala",
                }
        ]
}

What I want is:

{
        "project": "the lion king",
        "repository": "C:\\Users\\path\\to\\folder",
        "submodules": [
                {
                        "name": "mufasa",
                        "path": "example\\mufasa",
                },
                        {
                                "name": "simba",
                                "path": "example\\mufasa\\simba",
                        },
                {
                        "name": "nala",
                        "path": "example\\nala",
                }
        ]
}
0

There are 0 best solutions below