Python response.json() Method
Response.json() method of the Python Requests module is used to parse the HTTP response content assuming it is in JSON format. It decodes the JSON-encoded data into a Python dictionary using the built-in JSON decoder.
This method simplifies working with APIs by automatically handling JSON parsing by enabling easy access to structured data such as keys and values.
It's essential for retrieving and manipulating JSON data in web applications and API integrations, providing a straightforward way to interact with JSON APIs and extract information for further processing or display in Python programs.
Syntax
Following is the syntax and parameters of Response.json() method of the Python Requests module −
response.json()
Parameter
This method does not accept any parameters.
Return value
This method returns JSON data into a python dictionary.
Example 1
Following is the example of Response.json() method of the Python Requests module. Here Response.post() sends a POST request with a JSON payload (payload). The server's response containaing JSON data is then parsed using response.json() −
import requests
# JSON data to be sent in POST request
payload = {'key1': 'value1', 'key2': 'value2'}
# Send a POST request with JSON payload
response = requests.post('https://httpbin.org/post', json=payload)
# Parse JSON response
data = response.json()
# Access specific fields from response
print(data['data']) # Prints the JSON payload received by the server
Output
{"key1": "value1", "key2": "value2"}
Example 2
It's important to handle cases where the response might not be valid JSON. Using a try-except block ensures that if response.json() fails to parse the JSON data then raises a ValueError. So we can handle it by using the below example −
import requests
# Send a GET request
response = requests.get('https://www.tutorialspoint.com/market/login.jsp')
try:
# Parse JSON response
data = response.json()
# Access specific fields
print(data['login']) # Prints the tutorialspoint username
except ValueError:
print('Response is not valid JSON')
Output
Response is not valid JSON
python_modules.htm