1 year ago

#346321

test-img

PythonG

Getting the Depth of a json file in Python

I am pretty new to Python and I am currently working with json files. My task is to get the nesting depth of a data set.

 data= [{'medprice': '1144942',
  'medprice_ia': '1664657',
  'percentchngprice': '1.01',
  'percentchngpriceia': '0.64',
  'source': 'Zillow',
  'year': '2003',
  'zipcode': '94123'}]

JSON attribute with another object as value (or another object as member of a list value increases the depth of the file by 1

I tried some ideas and this one seems to work the best regarding this task but I believe that I am getting the wrong nesting depth because the code above should return 1 as a nesting depth and not 2.

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

The only thing I changed is reducing the return value to only the value: something like this

if type(x) is list and x:
    for a in x:
      value= max(str(depth(a)))
      return value

Is there a better way to figure this out? Or am I missing something? Cheers!

python

json

list

dictionary

depth

0 Answers

Your Answer

Accepted video resources