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

后端 未结 4 1164
栀梦
栀梦 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 20:58

    Taking a closer look at your Q, you want to get the depth from a JSON string. Here is a function I write:

    # This function count list/dict/tuple as levels
    def get_json_depth(s):
        d = {"(":")", "[":"]", "{":"}" }
        stack = []
        lefts = d.keys()
        rights = d.values()
    
        max_depth = 0
        depth = 0
        in_quotes = False
    
        for c in s:
                if c == '"':
                        in_quotes = not in_quotes
                if not in_quotes:
                        if c in lefts:
                                stack.append(c)
                                depth += 1
                                if depth > max_depth:
                                        max_depth = depth
                        elif c in rights:
                                if not stack:
                                        raise Exception()
                                if c != d[stack.pop()]:
                                        raise Exception()
        return max_depth
    

    But if you don't mind using json.loads(s) to convert it to dictionary, then use @Blorgbeard's recursive function.

    0 讨论(0)
  • 2021-01-06 21:20

    Here's one implementation:

    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
    
    0 讨论(0)
  • 2021-01-06 21:22

    You can find the depth using a recursive function like so.

    def depth(jsnFile):
        if jsnFile.has_key('children'):
           return 1 +  max([0] + map(depth, jsnFile['children']))
        else:
           return 1
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题