JSON树的深度 [英] Depth of a json tree
本文介绍了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":[
]
}
]
}
如何在python中找到树的最大深度?
How do I find maximum depth of the tree in python?
推荐答案
You can parse JSON with python's json library and then calculate depth with recursive function.
import json
def depth(jsn):
if jsn.has_key('children'):
return 1 + max([0] + map(depth, jsn['children']))
else:
return 1
j = json.load(file('your_file.json'))
print depth(j)
这篇关于JSON树的深度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文