检索嵌套json的级别

2024-05-29 03:02:28 发布

您现在位置:Python中文网/ 问答频道 /正文

有什么技术可以知道嵌套JSON将包含的级别数吗?你知道吗

例如:

animals = [
    {
        "animal" : {
            "type" : "bunny"
        }
    },
    {
        "animal" : {}
    },
    {}
]

Tags: jsontype级别技术animalsbunnyanimal
1条回答
网友
1楼 · 发布于 2024-05-29 03:02:28

您可以创建一个简单的递归函数:

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

相关问题 更多 >

    热门问题