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
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.