最后尝试学习Python。在阅读了有关该主题的所有其他问题后,我已经扣除了我是一个白痴。
我正在向一个开放的API发出Python请求,如下所示
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响应中的任何单个标记/节点。
答案 0 :(得分: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