Python 检索嵌套json的级别
有什么技术可以知道嵌套JSON将包含的级别数吗 例如:Python 检索嵌套json的级别,python,json,list,dictionary,Python,Json,List,Dictionary,有什么技术可以知道嵌套JSON将包含的级别数吗 例如: animals = [ { "animal" : { "type" : "bunny" } }, { "animal" : {} }, {} ] 您可以创建一个简单的递归函数: def get_depth(d): c = [1 if not isinstance(b, dict) else 1+get_depth(b)
animals = [
{
"animal" : {
"type" : "bunny"
}
},
{
"animal" : {}
},
{}
]
您可以创建一个简单的递归函数:
def get_depth(d):
c = [1 if not isinstance(b, dict) else 1+get_depth(b) for a, b in d.items()]
return max(c) if c else 0
animals = [{'animal': {'type': 'bunny'}}, {'animal': {}}, {}]
print(max(map(get_depth, animals)))
输出:
2
可能是一种递归方法。关于如何做到这一点,有很多答案。