简体   繁体   中英

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.

Seems like you just want a nested loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM