'Response'对象无法下标访问的Python http post请求

2024-04-26 00:25:17 发布

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

我试图发布一个HTTP请求。我已经设法使代码工作,但我正在努力返回一些结果。

结果是这样的

{
  "requestId" : "8317cgs1e1-36hd42-43h6be-br34r2-c70a6ege3fs5sbh",
  "numberOfRequests" : 1893
}

我正在尝试获取requestId,但我一直在获取错误响应“object is not subscribable

import json
import requests

workingFile = 'D:\\test.json'

with open(workingFile, 'r') as fh:
    data = json.load(fh)

url = 'http://jsontest'
username = 'user'
password = 'password123'

requestpost = requests.post(url, json=data, auth=(username, password))

print(requestpost["requestId"])

Tags: 代码importjsonhttpurldatausernamepassword
2条回答

您应该将响应转换为dict:

requestpost = requests.post(url, json=data, auth=(username, password))
res = requestpost.json()
print(res["requestId"])

response对象包含的信息比有效负载多得多。要获取POST请求返回的JSON数据,必须访问response.json(),如in the example所述:

requestpost = requests.post(url, json=data, auth=(username, password))
response_data = requestpost.json()
print(response_data["requestId"])

相关问题 更多 >