【问题标题】:Response' object is not subscriptable Python http post request响应'对象不可下标 Python http post 请求
【发布时间】:2026-02-21 12:35:02
【问题描述】:

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

结果是这样的

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

我正在尝试获取 requestId,但我不断收到错误 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"])

【问题讨论】:

    标签: python json post request


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您应该将您的回复转换为字典:

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

      【讨论】:

        【解决方案3】:

        响应不可读,因此您需要将其转换为可读格式, 我正在使用 python http.client

        conn = http.client.HTTPConnection('localhost', 5000)
        
        payload = json.dumps({'username': "username", 'password': "password"})
        headers = {'Content-Type': 'application/json'}
        conn.request('POST', '/api/user/register', payload, headers)
        response = conn.getresponse()
        print("JSON - ", response.read())
        

        如有要求,您可以查看上面的答案

        有时您必须使用json.loads() 函数来转换适当的格式。

        【讨论】: