Recursive function to create hierarchical JSON object?

后端 未结 5 1976
庸人自扰
庸人自扰 2021-02-08 19:08

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         


        
5条回答
  •  情歌与酒
    2021-02-08 19:29

    You could use this (a more compact and readable version)

    def get_child_nodes(node_id):   
        request = urllib2.Request(ROOT_URL + node_id)
        response = json.loads(urllib2.urlopen(request).read())
        return {
           "id":response['id'],
           "name":response['name'],
           "children":map(lambda childId: get_child_nodes(childId), response['childNode'])
        }
    
    get_child_nodes(ROOT_NODE)
    

提交回复
热议问题