To parse a JSON response in Python using the requests library, use the response.json() method. This method automatically converts the JSON response into a Python dictionary, allowing you to access data using standard dictionary syntax.
Key points:
Use
response.json()directly after making a request:import requests response = requests.get('https://api.example.com/data') data = response.json() print(data['key'])Always check the response status before parsing:
response.raise_for_status() # Raises an exception for bad status codes data = response.json()Handle potential errors with a try-except block:
try: data = response.json() except requests.exceptions.JSONDecodeError: print("Response is not valid JSON")
This approach is preferred over json.loads(response.text) because response.json() handles encoding automatically and is more concise.
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.
Answer from pswaminathan on Stack OverflowSince 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.
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().