Recursive function to create hierarchical JSON object?

后端 未结 5 2061
庸人自扰
庸人自扰 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:41

    You're not returning anything from each call to the recursive function. So, it seems like you just want to append each temp_obj dictionary into a list on each iteration of the loop, and return it after the end of the loop. Something like:

    def get_child_nodes(node_id):   
        request = urllib2.Request(ROOT_URL + node_id)
        response = json.loads(urllib2.urlopen(request).read())
        nodes = []
        for childnode in response['childNode']:
            temp_obj = {}
            temp_obj['id'] = childnode['id']
            temp_obj['name'] = childnode['name']
            temp_obj['children'] = get_child_nodes(temp_obj['id'])
            nodes.append(temp_obj)
        return nodes
    
    my_json_obj = json.dumps(get_child_nodes(ROOT_ID))
    

    (BTW, please beware of mixing tabs and spaces as Python isn't very forgiving of that. Best to stick to just spaces.)

提交回复
热议问题