Python从请求响应中获取第一项

2024-10-05 15:18:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python请求查询API,如下所示

url = "www.example.com"
response = requests.request("POST", url)

response
--------
[
  {
    "id": "485744",
    "descript": "firstitem",
  },
  {
    "id": "635456",
    "descript": "seconditem",
  },
  {
    "id": "765554",
    "descript": "thirditem",
  },
]

我正在尝试访问响应中的第一项,如下所示

response = response.json
print(response[0])

但是我得到了错误

TypeError: 'method' object is not subscriptable

我哪里做错了


Tags: comapiidjsonurlexampleresponserequest
2条回答

jsonResponse类的方法,而不是对象的属性。要获取json数据,请使用:

response = response.json()

您没有正确地将其命名为:response.json()

替代方法:

import json #import this on the top
response = json.loads(response) #You need to load the data into JSON

:每个^{末尾的附加逗号(,):

"firstitem""seconditem""thirditem"不是必需的,可能会出现错误

相关问题 更多 >