python - Decoding nested JSON with multiple 'for' loops -
i'm new python (last week), , have reached limit. spent 3 days on this, of time in stackoverflow, cannot work out how go further!
the json has multiple nested arrays. contain 3 (as example below (json.txt) does), or 30. need loop through each, drill down 'innings' , value of 'wickets'. it's last step i'm confused by. can advise?
yours in total desperation
will
import os, json,requests print 'starting' url = 'https://dl.dropboxusercontent.com/u/3758695/json.txt' # download json string json_string = requests.get(url) print 'downloaded json' # content the_data = json_string.json() print 'the_data has length ', len(the_data) index in range(len(the_data)): print 'now working on index ', index wicket in the_data[index]: print 'wicket equals ',wicket # ok - can see innings. now, how inside # , obtain 'wickets'?
first of all, don't use index loop directly on lists; way can give them meaningful names. top-level list of entries, each entry dictionary 'innings'
key, , each innings
list of dictionaries, with, among others, wickets
key:
for entry in data: inning in entry['innings']: print inning['wickets']
this prints:
>>> entry in data: ... inning in entry['innings']: ... print inning['wickets'] ... 10 9 0 0
this makes easier add information @ each level too:
>>> entry in data: ... print entry['description'] ... i, inning in enumerate(entry['innings']): ... print 'innings {}: {} wickets'.format(i + 1, inning['wickets']) ... rest of sri lanka v sri lanka @ pallekele, may 14, 2013 innings 1: 10 wickets innings 2: 9 wickets 63rd match: royal challengers bangalore v kings xi punjab @ bangalore, may 14, 2013 innings 1: 0 wickets innings 2: 0 wickets 64th match: chennai super kings v delhi daredevils @ chennai, may 14, 2013
Comments
Post a Comment