How to return a JSON response in Django?

Published On: 01/09/2022 | Category: Django


Hi Dev,

I will explain step by step tutorial how to return a json response in django. This tutorial will give you simple example of how to return json-encoded response. you can understand a concept of create a json response in django. This article goes in detailed on how to return a httpresponse in django. Alright, let’s dive into the steps.

JSON is a minimal, readable format for structuring data. It is utilized primarily to transmit data between a server and web application, as an alternative to XML. API's, lightweight replications, etc are rudimentary uses for a JSON string.

Here i explained simply step by step example of how to check if object is instance of model.

Example :1

In this example we will use for newer Django >= 1.7 django versions JsonResponse implemented in the django.http package which makes the things easier for you as you don't need to provide any content type or other information, only your data.

To pass any other JSON-serializable object you must set the safe parameter to False.

views.py
from django.http import JsonResponse

def index(request):
    responseData = {
        'id': 1,
        'name': 'Bhavesh Sonagra',
        'roles' : ['Admin','User']
    }

    return JsonResponse(responseData)
Example :2

In this second example we will use For older Django < 1.7django versions, you need to return a HttpResponse with the specific content type of JSON as second parameter.

views.py
import json
# for older versions (and using python < 2.7)
#from django.utils import simplejson
# and change the json.dumps for simplejson.dumps
from django.http import HttpResponse

def index(request):
    responseData = {
        'id': 1,
        'name': 'Bhavesh Sonagra',
        'roles' : ['Admin','User']
    }

    return HttpResponse(json.dumps(responseData), content_type="application/json")
Output
{  
   "id":1,
   "name":"Bhavesh Sonagra",
   "roles":[  
      "Admin",
      "User"
   ]
}

I hope it will help you....