Skip to content Skip to sidebar Skip to footer

Json Object Must Be Str, Not Response

I'm making a request to a URL that returns a JSON file, response = requests.get(url) response = json.loads(response) And then, I am attempting to go through some of the data, for

Solution 1:

You are trying to feed the response object to json.loads(). You don't get a string there, you'd have to access the .contents or .text attribute instead:

response = requests.get(url)
# Python 3response = json.loads(response.text)
# Python 2response = json.loads(response.content)

However, that'd be doing more work than you need to; requests supports handling JSON directly, and there is no need to import the json module:

response = requests.get(url).json()

See the JSON Response Content section of the requests Quickstart documentation.

Once loaded, you can get the doc key in the nested dictionary keyed on response:

for documents in response['response']['docs']:

Solution 2:

requests.get returns a response object, which contains status information, headers etc. You need to access the raw document text from this object in order to parse the json or just use the provided json method:

response = requests.get(url).json()

(minus error checking)

Post a Comment for "Json Object Must Be Str, Not Response"