在python中找到所有级别的孩子

时间:2015-03-14 12:42:43

标签: python json

我有一个

形式的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":[  

            ]
        }
    ]
}

我必须在树的各个层面找到孩子的数量。这意味着在任何级别我都应该知道孩子的数量和级别数。我无法弄清楚如何共同保持儿童的水平和数量。 我的意思是我需要有一个向量,我必须始终保持孩子及其等级数。

我能写的代码是

def children(node):
print node
for child in node:
    level=1
    children(child)

level=0
count=0
with open("t1.json") as fr:
    for line in fr:
        j2 = json.loads(line);
        for child in j2['children']:
            children(child)

1 个答案:

答案 0 :(得分:0)

从您的问题来看,我并不完全清楚您希望获得该信息的位置。例如,您可以将它放在树本身中:

import json
t = json.load("t1.json")

def annotateTree(t,l=0):
    t["level"] = l
    t["number_of_children"] = len(t["children"])
    for child in t["children"]:
        annotateTree(child, l+1)

annotateTree(t)

之后,在树的每个级别,您都会有两个新属性levelnumber_of_children