2017-08-02 61 views
2

試圖最終學習Python。讀過關於這個話題的所有其他問題後,我扣除了我是一個白癡。無法訪問Python中的JSON響應中的節點/標籤

我正在做一個Python請求開放的API像下面

import requests 
import json 

url = 'http://api.turfgame.com/v4/users' 
payload = [{"name": "tbone"}] 
headers = {'content-type': 'application/json'} 

r = requests.post(url, data=json.dumps(payload), headers=headers) 

這一切順利的話,我可以打印響應

print r.text 

然而,這是當我想訪問某些標籤/節點在我遇到的牆壁中。輸出是

[{"country":"se","medals":[34,54,13,5,46,28,16,6],"zones":[323,7577,14606],"pointsPerHour":21,"points":21809,"blocktime":17,"taken":2290,"name":"tbone","totalPoints":347388,"rank":30,"id":95195,"place":1931,"uniqueZonesTaken":269,"region":{"name":"Stockholm","id":141}}] 

而且我試着

rj = r.json() 
print rj['name'] 

但是,這只是給了我

Traceback (most recent call last): 
File "post.py", line 16, in <module> 
print rj['name'] 
TypeError: list indices must be integers, not str 

我不能讓我圍繞着如何獲取任何個人標籤/節點頭JSON響應。

回答

1

你得到的答覆:[{"country":"se",..."region":{"name":"Stockholm","id":141}}] 是JSON對象的列表(注意[]周圍的字典)。

所以,讓你的對象,你要做的:

rj = r.json() 
print rj[0]['name'] # the [0] to indicate you take the first element of your list