找到树上的所有孩子

时间:2015-03-10 11:34:18

标签: python

我有一个

形式的JSON树
{  
    "id":442500000904671234,
    "reply":0,
    "children":[  
        {  
            "id":442500532536893440,
            "reply":1,
            "children":[  
                {  
                    "id":442500826561785856,
                    "reply":1,
                    "children":[  
                        {  
                            "id":442501277688545280,
                            "reply":1,
                            "children":[  
                                {  
                                    "id":442501561940709376,
                                    "reply":1,
                                    "children":[  
                                        {  
                                            "id":442501884709199872,
                                            "reply":1,
                                            "children":[  

                                            ]
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        {  
            "id":442500099315597312,
            "reply":0,
            "children":[  

            ]
        }
    ]
}

现在,我想访问从根到叶子的根节点为442500000904671234的树的所有子节点。

使用以下python代码,我可以打印第一级孩子

import json
f=open('tree.txt','r')
for line in f:
    d=json.loads(line)
    print len(d["children"])
    for i in range (len(d["children"])):
        print d["children"][i]["id"]

如何让树上的所有孩子?

1 个答案:

答案 0 :(得分:1)

为了检索所有孩子,你可能需要递归:

import json

# method to recursively browse the elements
def get_children(node):
    for child in node['children']:
        yield child
        for grandchild in get_children(child):
            yield grandchild

# open the file and parse its JSON contents
f = open('tree.txt','r')
d = json.load(f)
f.close()

# display all the children found
for child in get_children(d):
    print child

有关详细信息,请阅读: