I am trying to find all the full path for specific key. I tried with recursion, i can able to get the values, but i can't able to track the path using my code. Any Help will definitely useful for me.
Input:
{
"id": ["0001"],
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": {
"id": ["1001"],
"type": "Regular"
}
},
"topping": [
{
"id": ["5001"],
"type": "None"
},
{
"id": ["5002"],
"type": "Glazed"
}
]
}
Expected Output:
[
{"id":["0001"]},
{"batters.batter.id":["1001"]},
{"topping[0].id":["5001"]},
{"topping[0].id":["5002"]}
]
Following code is i have used for get the values, but it doesn't helped me.
def json_extract(obj, key):
"""Recursively fetch values from nested JSON."""
arr = []
def extract(obj, arr, key):
"""Recursively search for values of key in JSON tree."""
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict)):
extract(v, arr, key)
elif k == key:
arr.append(v)
elif isinstance(obj, list):
for item in obj:
extract(item, arr, key)
return arr
values = extract(obj, arr, key)
return values