Depth Of A Json Tree
I have a tree of the form: { 'id':442500000904671234, 'reply':0, 'children':[ { 'id':442500532536893440, 'reply':1, 'c
Solution 1:
You can parse JSON with python's json library and then calculate depth with recursive function.
import json
defdepth(jsn):
if jsn.has_key('children'):
return1 + max([0] + map(depth, jsn['children']))
else:
return1
j = json.load(file('your_file.json'))
print depth(j)
Solution 2:
You can use a stack to push the { and then when you meet a } before you pop you check if your current depth is greater than the maximum depth that you got so far, that is if the stack.count is greater than the maximum count already achieved.
I'll update my answer after work with a code example
Solution 3:
What about loading json into dict
and traversing tree. At least should give some ideas to go further.
import json
defdepth(root):
if root isNone:
return0ifisinstance(root, list):
returnmax(map(depth, root)) + 1ifnotisinstance(root, dict):
return1returnmax(depth(v) for k, v in root.items()) + 1print depth(json.load(file('your_data.json')))
Solution 4:
I think you can just walk the tree using DFS or BFS and count the depth as you go:
#load in your data
json_tree = json.loads(your_data)
depth = 0
if json_tree:
depth += 1
#add a root node + it's depth
to_visit = [(json_tree, depth)]
max_depth = 0
while to_visit:
#get first from the list
current = to_visit.pop(0)
#if depth greater than the current max update max
if current[1] > max_depth:
max_depth = current[1]
# append all children to the list with increased depth
for child in current[0]['children']:
to_visit.append((child, current[1] + 1))
print(max_depth)
the benefit of doing it this way is that you actually go over your data structure rather than rely on the string representation
Solution 5:
convert json to dict,
count_global = 0deffind_depth(tree_dict=None, count=0):
ifnot tree_dict['children']:
global count_global
if count_global < count:
count_global = count
for child in tree_dict['children']:
count = count + 1
find_depth(child, count)
Post a Comment for "Depth Of A Json Tree"