What's the best way to parse a JSON response from the requests library?

PythonJsonRestPython Requests

Python Problem Overview


I'm using the python requests module to send a RESTful GET to a server, for which I get a response in JSON. The JSON response is basically just a list of lists.

What's the best way to coerce the response to a native Python object so I can either iterate or print it out using pprint?

Python Solutions


Solution 1 - Python

Since you're using requests, you should use the response's json method.

import requests

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

It autodetects which decoder to use.

Solution 2 - Python

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

Solution 3 - Python

You can use the json response as dictionary directly:

import requests

res = requests.get('https://reqres.in/api/users?page=2')
print(f'Total users: {res.json().get("total")}')

or you can hold the json content as dictionary:

json_res = res.json()

and from this json_res dictionary variable, you can extract any value of your choice

json_res.get('total')
json_res["total"]

Attentions Because this is a dictionary, you should keep your eye on the key spelling and the case, i.e. 'total' is not the same as 'Total'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionfelix001View Question on Stackoverflow
Solution 1 - PythonpswaminathanView Answer on Stackoverflow
Solution 2 - PythonSimeon VisserView Answer on Stackoverflow
Solution 3 - PythonAmado SaladinoView Answer on Stackoverflow