Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the elements from nested JSON with Python using json lib

Tags:

python

json

I want to list all the elements from "BoxDet" with the "BoxDet" name. The aim is to list it that way: BoxDet : ABC ...

A little part of my JSON:

{
   "id":1,
   "name":"BoxH",
   "readOnly":true,
   "children":[
      {
         "id":100,
         "name":"Box1",
         "readOnly":true,
         "children":[
            {
               "id":1003,
               "name":"Box2",
               "children":[
                  {
                     "id":1019,
                     "name":"BoxDet",
                     "Ids":[
                        "ABC",
                        "ABC2",
                        "DEF2",
                        "DEFHD",
                        "LKK"
                        ]
                    }
                ]
            }
        ]
    }
    ]
}

My problem is just on the beginning, I just cannot go deeper as first { }. My code...

output_json = json.load(open('root.json'))
for first in output_json:
    print first
    for second in first:
        print second

... returns me something like that:

readOnly
r
e
a
d
O
n
l
y
children
c
h
i
l
d
r
e
n

... an so on. I can't really even go deeper to Box1, not even mentioning Box2. I'm working with Python 2.7

like image 581
jakkolwiek Avatar asked Sep 18 '25 13:09

jakkolwiek


1 Answers

You need a tree-search algorithm for this:

def locateByName(e,name):
    if e.get('name',None) == name:
        return e

    for child in e.get('children',[]):
        result = locateByName(child,name)
        if result is not None:
            return result

    return None

Now you can use this recursive function to locate the element you want:

node = locateByName(output_json, 'BoxDet')
print node['name'],node['Ids']
like image 173
Aaron Digulla Avatar answered Sep 21 '25 03:09

Aaron Digulla