Python requests JSON to a dict
response.json() decodes the body. You get a dict when that body is a JSON object, and a list when it is a JSON array.
response.json() is json.loads() on the body
JSON on the wire is text. A Python dict is the object you get after parsing. response.json() reads response.text and parses it. You do not call json.loads() again on the result.
import requests
response = requests.get("https://example.com/user.json", timeout=10)
response.raise_for_status()
data = response.json()
print(data["name"])
timeout stops a hung connection. raise_for_status() raises before you parse when the server returns an error status. An error page is often HTML, and parsing it as JSON produces a less useful exception. The same .json() call is what people mean by “python requests json to dict”.
Invalid JSON is a decode error, not an HTTP error
import requests
response = requests.get("https://example.com/user.json", timeout=10)
response.raise_for_status()
try:
data = response.json()
except requests.exceptions.JSONDecodeError as exc:
print(f"Body is not JSON: {exc}")
requests.exceptions.JSONDecodeError is the exception current requests raises for a body that is not JSON. It subclasses the decode error of whichever JSON library requests is using. A 200 response can still be invalid JSON. A dict result does not prove the fields you need are present: a missing key and JSON null are different, as described in null vs missing.
Calling json.loads(response.json()) fails when the first call already returned a dict, and it hides a double-encoded body when the first call returned a string. Check type(data) before decoding again.
Pass a dict to the json= argument
To send JSON, pass the dict to json=. Requests serializes it and sets Content-Type: application/json.
import requests
payload = {"name": "Ada", "active": True}
response = requests.post("https://example.com/users", json=payload, timeout=10)
response.raise_for_status()
Do not pre-encode the dict and also pass json=. json=json.dumps(payload) encodes a string, so the body is a JSON string containing another document. Pass the dict, or pass the encoded text as data= and set the content type yourself. True becomes true during that serialization. Details of json.dumps() are in the dict to JSON guide.
An API object becomes a dict; an API array becomes a list
| JSON body | response.json() |
|---|---|
{"name": "Ada"} | dict |
[{"name": "Ada"}] | list of dicts |
null | None |
| A JSON string of another document | str — decode once more only if that is the contract |
Nested JSON objects are nested dicts. That is the whole relationship: the response is text that follows the JSON grammar, and response.json() builds ordinary Python values from it. For a string you already have, use json.loads(). For a file, use json.load(). To see which fields changed between two saved responses, use the API comparison guide.