问题描述
我正在学习使用Python和API(特别是此世界杯API, http://www.kimonolabs.com/worldcup /explorer )
I am learning to use Python and APIs (specifically, this World Cup 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中的所有名字.这就是我所拥有的:
I am simply trying to print all of the firstNames in this API. Here's what I have:
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"
But when I run it, I get the error "...line 8, in ...TypeError: list indices must be integers, not str"
我一直在寻找解决方案,但是似乎发现了更多更深入"的API问题,但我还不是很了解,因此对我需要做的任何帮助或解释都将是惊人的.谢谢!
I have looked around for solutions, but seem to find questions to more "in depth" API questions and I don't really understand it all yet, so any help or explanation as to what I need to do would be amazing. Thank you!
推荐答案
首先,您应该使用json.loads
,而不是json.dumps
. loads
将JSON源文本转换为Python值,而dumps
则相反.
First of all, you should be using json.loads
, not json.dumps
. loads
converts JSON source text to a Python value, while dumps
goes the other way.
解决此问题后,根据问题顶部的JSON代码段,readable_json
将成为列表,因此readable_json['firstName']
没有意义.获取列表中每个元素的'firstName'
字段的正确方法是消除playerstuff = readable_json['firstName']
行并将for i in playerstuff:
更改为for i in readable_json:
.
After you fix that, based on the JSON snippet at the top of your question, readable_json
will be a list, and so readable_json['firstName']
is meaningless. The correct way to get the 'firstName'
field of every element of a list is to eliminate the playerstuff = readable_json['firstName']
line and change for i in playerstuff:
to for i in readable_json:
.
这篇关于Python和JSON-TypeError列表索引必须是整数而不是str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!