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

后端 未结 4 1200
栀梦
栀梦 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.

提交回复
热议问题