TypeError:'Response'对象没有属性'__getitem__'

时间:2015-09-19 07:40:27

标签: 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'])

2 个答案:

答案 0 :(得分:11)

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

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

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

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

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

最后但并非最不重要的是,如果API使用JSONRPC作为协议,您可以使用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()

答案 1 :(得分:1)

只需更改源代码:

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

 print("respone is: ", response['result'].encode('utf-8'))

确实,单独的响应对象不能被编入索引,而是为了这个目的,您需要在json format中返回信息(按顺序解析响应信息),您可以使用{{{ 1}}和 这里为了获得正确的字符串,你必须使用utf-8对其进行编码(否则你的输出将是这样的-u' LikeThis)

相关问题