How to find the maximum “depth” of a python dictionary or JSON object?

后端 未结 4 1161
栀梦
栀梦 2021-01-06 20:41

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

4条回答
  •  时光说笑
    2021-01-06 21:23

    def depth(d):
        if hasattr(d, "values"):
            return 1 + max(map(depth, d.values()))
        if hasattr(d, "__len__") and not hasattr(d, "lower"):
            return 1 + max(map(depth, d))
        return 0
    

提交回复
热议问题