我正在学习使用Python和API(特别是此世界杯API,http://www.kimonolabs.com/worldcup/explorer)
JSON数据如下所示:
[ { "firstName": "Nicolas Alexis Julio", "lastName": "N'Koulou N'Doubena", "nickname": "N. N'Koulou", "assists": 0, "clubId": "5AF524A1-830C-4D75-8C54-2D0BA1F9BE33", "teamId": "DF25ABB8-37EB-4C2A-8B6C-BDA53BF5A74D", "id": "D9AD1E6D-4253-4B88-BB78-0F43E02AF016", "type": "Player" }, { "firstName": "Alexandre Dimitri", "lastName": "Song-Billong", "nickname": "A. Song", "clubId": "35BCEEAF-37D3-4685-83C4-DDCA504E0653", "teamId": "DF25ABB8-37EB-4C2A-8B6C-BDA53BF5A74D", "id": "A84540B7-37B6-416F-8C4D-8EAD55D113D9", "type": "Player" }, ]
我只是试图打印此API中的所有名字。这是我所拥有的:
import urllib2 import json url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx" json_obj = urllib2.urlopen(url).read readable_json = json.dumps(json_obj) playerstuff = readable_json['firstName'] for i in playerstuff: print i['firstName']
但是当我运行它时,出现错误“ … TypeError,… TypeError:列表索引必须是整数,而不是str”。
我四处寻找解决方案,但似乎发现了更多“更深入”的API问题,但我还不是很了解,因此对我需要做的任何帮助或解释都将是惊人的。谢谢!
首先,您应该使用json.loads而不是json.dumps。 loads将JSON源文本转换为Python值,反之dumps则相反。
json.loads
json.dumps
loads
dumps
修复该问题之后,readable_json将根据问题顶部的JSON代码段列出该列表,因此readable_json['firstName']毫无意义。获取'firstName'列表中每个元素的字段的正确方法是消除该playerstuff = readable_json['firstName']行并更改for i in playerstuff:为for i in readable_json:。
readable_json
readable_json['firstName']
'firstName'
playerstuff = readable_json['firstName']
for i in playerstuff:
for i in readable_json: