TypeError: the "Response" object does not have the "__getitem__" attribute

I try to get the value from the response object in the dictionary, but I continue to encounter this error, I am mistaken in thinking that you are __getitem__ more often used for indexing in classes?

Here is the code:

 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']) 
+6
source share
2 answers

The response object is not a dictionary; you cannot use its indexing.

If the API returns a JSON response, you need to use response.json() to decode it to a Python object:

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

Note that you do not need to encode JSON request data; you can just use the json argument to the request.post() method here; this also sets the Content-Type header for you:

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

Last but not least, if the API uses JSONRPC as the protocol, you can use the jsonrpc-requests project to call the proxy method for you

 from jsonrpc_requests import Server url = "http://public.coindaddy.io:4000/api/" server = Server(url, auth=('rpc', '1234')) result = server.get_running_info() 
+8
source

Just change the source code a bit like

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

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

It is true that only the response object cannot be indexed for this purpose, you need to return the information in json format (for information about the response to parsing), which you can do using json () and Here, to get the correct line, you should encode it using utf-8 (your other wise output would be something like this -u'LikeThis)

+1
source

All Articles