用于创建分层JSON对象的递归函数?

flo*_*fan 9 python algorithm recursion json

我不是一个足够好的计算机科学家自己解决这个问题:(

我有一个返回JSON响应的API,如下所示:

// 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
Run Code Online (Sandbox Code Playgroud)

我想以递归方式解析它并构建一个类似于下面的分层JSON对象:

{ id: 200,
  name: 'France', 
  children: [
     { id: 400,
       name: 'Paris',
       children: [...]
     },
     { id: 500,
       name: 'Lyon', 
       children: [...]
     } 
  ],
} 
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有这个,它解析树的每个节点,但不保存到JSON对象.如何将其展开以将其保存到JSON对象中?

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)
Run Code Online (Sandbox Code Playgroud)

这不是功课,但也许我需要做一些功课来更好地解决这类问题:(谢谢你的任何帮助.

Jan*_*ila 6

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)
Run Code Online (Sandbox Code Playgroud)