How to return a JSON response in Django


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

In thsi article, you will learn how to return a JSON response properly in all the versions of Django.

Django >= 1.7

For newer django versions, you can use the 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.

from django.http import JsonResponse

def index(request):
    responseData = {
        'id': 4,
        'name': 'Test Response',
        'roles' : ['Admin','User']
    }

    return JsonResponse(responseData)

As a lot of web framework does, to return a "class" as response is the preferred method by most developers.

Django < 1.7

For older django versions, you need to return a HttpResponse with the specific content type of JSON as second parameter.

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': 4,
        'name': 'Test Response',
        'roles' : ['Admin','User']
    }

    return HttpResponse(json.dumps(responseData), content_type="application/json")

Note: you can still using this method if you want on the newer versions.

As the JsonResponse class doesn't exist you'll need to use the old school way, not so quick to write but functional.

The ouput of both responses will be :

{  
   "id":4,
   "name":"Test Response",
   "roles":[  
      "Admin",
      "User"
   ]
}

As expected. Have fun !

Become a more social person