JSON is the common format which is used to exchange information between the HTTP client and the server. In this article, we will see how to read JSON data from an incoming request in Django and extract the information from it for further processing.
It is recommended to go through the Django views before referring to this article.
Please also make sure Django is installed. If not, use the following command to install the Django.
pip install django
Let’s get started by importing the required modules.
from django.http import JsonResponse
import json
In the above example, the JsonResponse
module is used to send a JSON response back to the client, while the json
module provides functions for working with JSON data.
Read the JSON data from request
To read the JSON data from the incoming request, you can use the request.body
attribute, which contains the raw HTTP request body data. Convert this data to a JSON object using the json.loads()
function.
def my_view(request):
if request.method == 'POST':
data = json.loads(request.body)
# Perform operations on the JSON data
In the above example, we assume that the JSON data is sent via a POST request. You can modify the HTTP method based on your requirement.
Extract and process JSON data
As we have the JSON data, we can extract the necessary information and perform the operations on it.
def my_view(request):
if request.method == 'POST':
data = json.loads(request.body)
# Extract information from the JSON data
name = data['name']
age = data['age']
# Perform operations on the extracted data
# Return a JSON response
return JsonResponse({'message': 'Data saved successfully'})
In the above example, we extract the name
and age
fields from the JSON data and returned the response to the client after processing the above-extracted data.
Following is the complete example:
from django.http import JsonResponse
import json
def my_view(request):
if request.method == 'POST':
data = json.loads(request.body)
# Extract information from the JSON data
name = data['name']
age = data['age']
# Perform operations on the extracted data
# Example: Create a new object using the extracted values
new_object = MyModel(name=name, age=age)
new_object.save()
# Return a JSON response
return JsonResponse({'message': 'Data saved successfully'})