string indices must be integers while parsing JSON - python -
i new python , facing error: string indices must integers
while parsing json file.
json file:
{"nflteams": [ {"code":"ari","fullname":"arizona cardinals","shortname":"arizona"}, {"code":"atl","fullname":"atlanta falcons","shortname":"atlanta"}, {"code":"was","fullname":"washington redskins","shortname":"washington"} ]}
my code:
import urllib.request ur import urllib.parse import json url = 'http://www.fantasyfootballnerd.com/service/nfl-teams/json/test/' user_agent = 'mozilla/5.0 (windows nt 6.1; win64; x64)' values = {'name' : 'michael foord', 'location' : 'northampton', 'language' : 'python' } headers = { 'user-agent' : user_agent } data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.request(url, data, headers) response = urllib.request.urlopen(req) the_page = response.read().decode('utf-8') print (the_page) team_data = json.loads(the_page) print (type(team_data)) // team_data type dict item in team_data: print (item['nflteams'][0]["code"]) print (item['nflteams'][0]['fullname']) print (item['nflteams'][0]['shortname'])
i have tried print following:
print (item['nflteams']["code"])
and this:
for item in team_data['nflteams'].values(): print (item["code"]) print (item['fullname']) print (item['shortname'])
which gives me error:
for item in team_data['nflteams'].values(): attributeerror: 'list' object has no attribute 'values'
can please me figure out what's going on? thank you.
.values()
used loop through values of dictionary however, team_data['nflteams']
list
containing dictionaries. thus, need remove .values()
access each dictionary whilst iterating:
for item in team_data['nflteams']: print (item["code"]) print (item['fullname']) print (item['shortname'])
if want use .values()
:
for item in team_data.values()[0]: print (item["code"]) print (item['fullname']) print (item['shortname'])
please keep in mind .values()
returns view object in python 3.x, need force evaluating using list()
in order access elements index:
for item in list(team_data.values())[0]:
Comments
Post a Comment