How to find the maximum "depth" of a python dictionary or JSON object? -
i have json string , want know maximum depth is. depth mean number of embedded keys. if 1 key 7 "children" , know other key had many, depth 8.
since types (i believe) can embed other objects arrays , other dictionaries need checked. there way check this?
i hoping achieve without external modules if not targeting python3.
note: here mean "depth"
the following dictionary:
{ "path": "/0001_anthem", "name": "0001_anthem", "ismovie": true, "runtime": 3600, "thumbnaillocation": "/thubs/test.png", "id": 1, "media": [ { "path": "/0001_anthem/louvers.mp4", "name": "louvers.mp4" } ] }
would have "depth" or length of 3
because farthest embedded item key/value pair (level 3) in media
array (level 2), in main dictionary
(level 1). not sure terminology others use, terminology think make sense.
thanks
here's 1 implementation:
def depth(x): if type(x) dict , x: return 1 + max(depth(x[a]) in x) if type(x) list , x: return 1 + max(depth(a) in x) return 0
Comments
Post a Comment