4

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

4 Answers 4

10

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']
Sign up to request clarification or add additional context in comments.

6 Comments

Hi Aaron, @Aaron Digulla, another one question. Your solution worked for me as a charm. I'm trying right now to change your code to deliver me in result not the Ids, but the "name" values itself. [pastebin.com/MDPv0PND] this is my json, I want to extract the SUB, SUBSUB and NAME and when using a quasi for-chain, I cound not get back in hierarchy to get the SUBSUB2... Could you please put me somehow on the right track?
Ask a new question, please.
@AaronDigulla, why do you need to guard the return result in the for loop? Can't you just return result and leave out the return None at the end?
@Chielt Without the guard, it would only consider the first child.
|
1

when you try to use a for loop on a dict, without any special consideration, you get only the keys out of the dict. That is:

>>> my_dict = {'foo': 'bar', 'baz':'quux'}
>>> list(my_dict)
['foo', 'baz']
>>> for x in my_dict:
...     print repr(x)    
'foo'
'baz'

The most usual thing to do is to use dict.iteritems() (just dict.items() in python 3)

>>> for x in my_dict.iteritems():
...     print repr(x)
('foo', 'bar')
('baz', 'quux')

Or you can fetch the value for the key yourself:

>>> for x in my_dict:
...     print repr(x), repr(my_dict[x])    
'foo' 'bar'
'baz' 'quux'

Comments

1

If you want to iterate through the children of your entities you can do the following:

for children in output_json["children"]:
    #Going down to ID: 100 level
    for grandchildren in children["children"]:
        #Going down to ID: 1003 level
        for grandgrandchildren in grandchildren["children"]:
            #Going down to ID: 1019 level
            if grandgrandchildren["name"] == "BoxDet":
                return "BoxDet" + " ".join(grandgrandchildren["Ids"])

Not that the data structure involved in the json module works more or less like classic dictionary where you access the value through the key:

my_dict[key] = value

1 Comment

When you use a for-in on a dictionary it iterates on all the key inside the dictionary. "for key in dictionary"
0

try it like this:

output_json = json.load(open('root.json'))
if "children" in output_json:
  children = output_json["children"]
  if "children" in children:
    children1 = children["children"]
    if "children" in children1:
      children2 = children1["children"]
      if "name" in children2:
        name = children2["name"]
      if "Ids" in children2:
        ids = children2["Ids"]
      print name, ids

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.