响应'对象不是可下标的 Python http post 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34508981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Response' object is not subscriptable Python http post request
提问by tosh
I am trying to post a HTTP
request. I have managed to get the code to work but I am struggling returning some of the result.
我正在尝试发布HTTP
请求。我已经设法让代码工作,但我正在努力返回一些结果。
The result looks like this
结果看起来像这样
{
"requestId" : "8317cgs1e1-36hd42-43h6be-br34r2-c70a6ege3fs5sbh",
"numberOfRequests" : 1893
}
I am trying to get the requestId but I keep getting the error Response' object is not subscriptable
我正在尝试获取 requestId 但我不断收到错误响应'对象不可下标
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"])
采纳答案by Finwood
The response
object contains much more information than just the payload. To get the JSON data returned by the POST request, you'll have to access response.json()
as described in the example:
该response
对象包含的信息远不止有效载荷。要获取 POST 请求返回的 JSON 数据,您必须按照示例中的response.json()
描述进行访问:
requestpost = requests.post(url, json=data, auth=(username, password))
response_data = requestpost.json()
print(response_data["requestId"])
回答by Pierre Michard
You should convert your response to a dict:
您应该将您的回复转换为字典:
requestpost = requests.post(url, json=data, auth=(username, password))
res = requestpost.json()
print(res["requestId"])