我正在尝试解析Python中的JSON数据。我通过requests.get()
电话获得了数据并将其存储在resp
中,然后我正在尝试阅读它:
try:
for item in resp.json():
print item
except:
e = sys.exc_info()[0]
print "Bad Request\n"
print e
哪个给了我
standing
leagueCaption
matchday
_links
我想要的信息是有效的,但是当我尝试print item['standing']
时,我会抛出<type 'exceptions.TypeError'>
异常并且测试失败。可以找到JSON数据Here
{
"_links": {
"self": {
"href": "http:\/\/api.football-data.org\/v1\/competitions\/426\/leagueTable\/?matchday=26"
},
"competition": {
"href": "http:\/\/api.football-data.org\/v1\/competitions\/426"
}
},
"leagueCaption": "Premier League 2016\/17",
"matchday": 26,
"standing": [
{
"_links": {
"team": {
"href": "http:\/\/api.football-data.org\/v1\/teams\/61"
}
},
"position": 1,
"teamName": "Chelsea FC",
"crestURI": "http:\/\/upload.wikimedia.org\/wikipedia\/de\/5\/5c\/Chelsea_crest.svg",
"playedGames": 25,
"points": 60,
"goals": 52,
"goalsAgainst": 18,
"goalDifference": 34,
"wins": 19,
"draws": 3,
"losses": 3,
"home": {
"goals": 33,
"goalsAgainst": 7,
"wins": 11,
"draws": 0,
"losses": 1
},
"away": {
"goals": 19,
"goalsAgainst": 11,
"wins": 8,
"draws": 3,
"losses": 2
}
},
我也试过了item['standing']['position']
,但也失败了。
答案 0 :(得分:2)
您尝试使用的item
不是json字典。尝试做:
data = resp.json()
print(data['standing'])
由于您仍然遇到问题,这可能是您所追求的确切代码:
import requests
response = requests.get('http://api.football-data.org/v1/competitions/426/leagueTable')
data = response.json()
print(data['standing'])
请注意,我根本不使用for循环,因为它不是必需的。