How to parse JSON in Python Django

In this Python Django tutorial, we will learn about JSON and how to parse it in Python Django.

What is JSON

JSON stands for Javascript Object Notation. It is a text format for storing and transporting data and it is also considered a “self-describing” function because it is easy to understand. It is used to represent data structures in web applications. Python also consists of a Json module as inbuilt support to work with JSON data.

How to parse JSON in Python Django?

To understand how to parse JSON in Python Django first see an example of a JSON string.

'{"name":"james", "role":"developer", "salary":40000}'

We will use the inbuilt module ‘json‘ to parse the JSON in Python Django. An example is shown below to understand how JSON is parsed in Python.

import json

employee = '{"name":"james", "role":"developer", "salary":40000}'

data = json.loads(employee)

print("NAME:", data["name"])
print("ROLE:", data["role"])
JSON parse in Python Django
Parsing JSON in Python Django

In Django parsing, a JSON is similar to what is in Python. Here also we use json module to parse JSON in Django views. Below an example is shown in code form.

import json
from django.http import JsonResponse, HttpResponseBadRequest

def my_view(request):
    if request.mrthod == 'POST':
        try:
            data = json.loads(request.body) 
            name = employee['name']
            role = employee['role']
            salary = employee['salary']

            response_data = {'status':'success'}
            return JsonResponse(response_data)
        except json.JSONDecodeError:
            return HttpResponseBadRequest('Invalid Json')
    else: 
        return HttpResponseBadRequest('Unsupported Method')
    

In the above code ‘my_view‘ handles the POST request and used ‘json.loads()’ to parse the request body as JSON. HttpBadRequest will return an error when the JSON is invalid.

So, this is how we can parse JSON in Python Django.

READ:  How to Get HTML Code from Rich Text in Python Django

Conclusion

In this tutorial, we came to know about json module through which we can parse JSON in Python Django and also learned through which method json module parse data in Python and Django.

You may also like to read the following articles: