PoweredByCoffee PoweredByCoffee - 4 months ago 9
JSON Question

Python for Each Json Element

Having a little trouble parsing JSON with Python and I'm not really sure what the syntax is I'd need.

The structure looks like this

name = (json_data['JsonResultTitle']['Loc']['List'][0]['Events'][0]['Name'])


The numbers after
List
and
Events
can both change.

I was able to iterate through the
List
ones using something ugly like:

namecounter = 0
try:
name = (json_data['JsonResultTitle']['Loc']['List'][namecounter]['Events'][0]['Name'])
namecounter +=1
except:
print "stop"


And I could technically embed another loop in there which runs until another exception for the
Events
counter but there has to be a neater way of doing this.

Something like this might be neater but it still doesn't strike me as the right way of doing things either:

counter = 0
secondcounter = 0
for i in json_data['JsonResultTitle']:
try:
print i['Loc']['List'][counter]['Events'][0]['Name']
except:
print "no first"
counter +=1
try:
print i['Loc']['List'][counter]['Events'][secondcounter]['Name']
except:
print "no second"
secondcounter +=1


This might be blindingly obvious but I can't see the proper way of doing this.

I'd really appreciate a nudge in the right direction.

Answer

Seems like you just want a nested loop.

for item in json_data['JsonResultTitle']['Loc']['List']:
    for event in item['Events']:
        print event['Name']
Comments