'parse to child element of nested JSON using python

Suppose our JSON file has data:

[{
"key1": "value",
"key2": [{
        "key1": "value",
        "key2": [{
                "key1": "value",
                "key2": "value"
            }]              
    },
    {
        "key1": "value",
        "key2": "value"
    }]
}]

In this case, I can access the child using:

with open (filename) as f:
     data = json.load(f)

data[0]['key2'][0]['key2']

But how can I access child element if I dont know how many times it is nested? Is there a way to generate pattern like data[0]['key2'][0]['key2'][0]['key2'][0]['key2'] or a better way of accessing child.

PS: After accessing child element I would need to modify it and then save it in the same source file.



Solution 1:[1]

It might help you https://linuxhint.com/python-dictionary-length/#:~:text=Using%20the%20built%2Din%20function,by%20the%20len()%20function.

or you can use the nested loops and calculate the length of the upcoming key

for x in fruits:
    print(x)
    for y in x:
        print(y)
        len(y)....

Solution 2:[2]

the best way I can think is with a recursive function

def recursive(json):
    for value in json:
        # value condition
        if str(value):
            print(value)
            break
        else:
            recursive(value)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 S.B
Solution 2