python - 类型错误 : 'Response' object has no attribute '__getitem__'

标签 python json python-requests json-rpc

我试图从字典中的响应对象中获取一个值,但我一直遇到这个错误,我认为你 __getitem__ 更常用于类中的索引是不是我错了?

代码如下:

import json
import requests
from requests.auth import HTTPBasicAuth

url = "http://public.coindaddy.io:4000/api/"
headers = {'content-type': 'application/json'}
auth = HTTPBasicAuth('rpc', '1234')

payload = {
  "method": "get_running_info",
  "params": {},
  "jsonrpc": "2.0",
  "id": 0,
}

response = requests.post(url, data=json.dumps(payload), headers=headers,   auth=auth)


print("respone is: ", response['result'])

最佳答案

响应对象不是字典,不能对其使用索引。

如果 API 返回 JSON response , 你需要使用 response.json() method将其解码为 Python 对象:

data = response.json()
print("respone is: ", data['result'])

请注意,您也不必对请求的 JSON 数据进行编码;你可以在这里使用 json 参数到 request.post() 方法;这也为您设置了 Content-Type header :

response = requests.post(url, json=payload, auth=auth)

最后但同样重要的是,如果 API 使用 JSONRPC 作为协议(protocol),您可以使用 jsonrpc-requests project为您代理方法调用:

from jsonrpc_requests import Server

url = "http://public.coindaddy.io:4000/api/"
server = Server(url, auth=('rpc', '1234'))

result = server.get_running_info()

关于python - 类型错误 : 'Response' object has no attribute '__getitem__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32665659/

相关文章:

javascript - 在运行时问题将 JSON 对象添加到 JSON 数组

json - 响应数据为零

python - 获取与 urlopen 一起使用的 urllib.requests 证书包

python - 单元测试 python 请求?

python-3.x - 使用 Python 的 SOAP 请求

python - 用 Beautiful Soup 提取 href

python - 如何让 Pycharm 找到我想要在代码中使用的文件?

c# - 在具有动态对象名称的 JSON 上使用 JsonConvert.DeserializeObject

python - Django:get_absolute_url 不起作用

python - 写入 uWSGI unix socket