响应"对象不可下标Python http发布请求 [英] Response' object is not subscriptable Python http post request

查看:141
本文介绍了响应"对象不可下标Python http发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发布HTTP请求.我设法使代码正常工作,但是我在努力返回一些结果.

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.

结果看起来像这样

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

我正在尝试获取requestId,但我一直收到错误Response'对象无法下标

I am trying to get the requestId but I keep getting the error Response' object is not subscriptable

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"])

推荐答案

response对象包含的信息不仅仅是有效载荷.要获取POST请求返回的JSON数据,您必须按

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:

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

这篇关于响应"对象不可下标Python http发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆