Recursive function to create hierarchical JSON object?
algorithm, json, python, recursion
Solution
def get_node(node_id):
request = urllib2.Request(ROOT_URL + node_id)
response = json.loads(urllib2.urlopen(request).read())
temp_obj = {}
temp_obj['id'] = response['id']
temp_obj['name'] = response['name']
temp_obj['children'] = [get_node(child['id']) for child in response['childNode']]
return temp_obj
hierarchy = get_node(ROOT_NODE)
Problem
I'm just not a good enough computer scientist to figure this out by myself :( I have an API that returns JSON responses that look like this: ``` // call to /api/get/200 { id : 200, name : 'France', childNode: [ id: 400, id: 500] } // call to /api/get/400 { id : 400, name : 'Paris', childNode: [ id: 882, id: 417] } // call to /api/get/500 { id : 500, name : 'Lyon', childNode: [ id: 998, id: 104] } // etc ``` I would like to parse it recursively and build a hierarchical JSON object that looks something like this: ``` { id: 200, name: 'France', children: [ { id: 400, name: 'Paris', children: [...] }, { id: 500, name: 'Lyon', children: [...] } ], } ``` So far, I have this, which does parse every node of the tree, but doesn't save it into a JSON object. How can I expand this to save it into the JSON object? ``` hierarchy = {} def get_child_nodes(node_id): request = urllib2.Request(ROOT_URL + node_id) response = json.loads(urllib2.urlopen(request).read()) for childnode in response['childNode']: temp_obj = {} temp_obj['id'] = childnode['id'] temp_obj['name'] = childnode['name'] children = get_child_nodes(temp_obj['id']) // How to save temp_obj into the hierarchy? get_child_nodes(ROOT_NODE) ``` This isn't homework, but maybe I need to do some homework to get better at solving this kind of problem :( Thank you for any help.