I have json
[
{
"id": 1116,
"en_name": "Location, Surroundings",
"children": [
{
"id": 819,
"en_name": "Location Satisfaction",
"children": []
},
{
"id": 1004,
"en_name": "Car Parking Facilities",
"children": [
{
"id": 1297,
"en_name": "Availability and general perception of parking",
"children": []
}
]
},
{
"id": 1123,
"en_name": "On the road ",
"children": []
}
]
}
]
I need to find the id and get the name.
For example, if I ask the algorithm to find a name by ID 1297, then it should give
me "Accessibility and general perception of parking".
The algorithm should run through the entire array of the dictionary and also run through all "children", which may also contain "children"
while True:
for data in self.main_taxonomy:
while len(data["children"]) != 0:
if data["id"] == id:
return data["name"]
else:
data = data["children"]
I tried to do it this way, but it didn’t check all the nesting.
2
Answers
Define a recursive function like this:
This function will return a
en_name
property ifid
matches else returnsNone
, call it on mainarray
of your json likerecursive_find(<your_id_here>, data)
This can be solved as a recursive function:
Example use:
Output: