如何找到最大的“深度"? python字典或JSON对象的概念? [英] How to find the maximum "depth" of a python dictionary or JSON object?

查看:108
本文介绍了如何找到最大的“深度"? python字典或JSON对象的概念?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json字符串,我想知道它的最大深度是多少.所谓深度,是指嵌入式密钥的数量.因此,如果一个键有7个孩子",而又知道另一个键有那么多,则深度为8.

I have a json string and I want to know what its maximum depth is. By depth I mean the number of embedded keys. So if one key as 7 "children" and know other key had that many, the depth would be 8.

由于(我相信)唯一可以嵌入其他对象的类型是需要检查的所有数组和其他字典.有办法检查吗?

Since the only types (I believe) that can embed other objects are arrays and other dictionaries that is all that would need to be checked. Is there a way to check this?

我希望在没有外部模块的情况下实现这一目标,但如果没有,我的目标是python3.

I was hoping to achieve this without external modules but if not I am targeting python3.

注意:这就是我所说的深度"

以下字典:

{
  "path": "/0001_Anthem",
  "name": "0001_Anthem",
  "isMovie": true,
  "runtime": 3600,
  "thumbnailLocation": "/thubs/test.png",
  "id": 1, 
  "media": [
    {
      "path": "/0001_Anthem/louvers.mp4",
      "name": "louvers.mp4"
    }
  ]
}

的深度"或长度为"3",因为最远的嵌入项是主dictionary(级别1)中的media数组(级别2)中的键/值对(级别3). ).我不确定其他人使用什么术语,这只是我认为有意义的术语.

Would have a "depth" or length of 3 because the farthest embedded item is the key/value pair (level 3) in the media array (level 2), in the main dictionary (level 1). I am not sure what terminology others use, this is just the terminology I think make sense.

谢谢

推荐答案

这里是一个实现:

def depth(x):
    if type(x) is dict and x:
        return 1 + max(depth(x[a]) for a in x)
    if type(x) is list and x:
        return 1 + max(depth(a) for a in x)
    return 0

这篇关于如何找到最大的“深度"? python字典或JSON对象的概念?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆