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.
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)....
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.