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.
CodePudding user response:
It might help you https://linuxhint.com/python-dictionary-length/#:~:text=Using the built-in function,by the len() function.
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)....
CodePudding user response:
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)