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