How to return a JSON response in Django?

Published On: 25/03/2025 | Category: Django
How to return a JSON response in Django

Hi Dev,

Welcome to a step-by-step tutorial on how to return a JSON response in Django. In this guide, you'll learn with easy examples how to return a JSON-encoded response using both modern and legacy methods. We’ll look at how to use Django’s JsonResponse and HttpResponse for APIs or dynamic web responses.

JSON is a lightweight and human-readable data format used commonly in web APIs to transmit structured data between server and client. Django provides multiple ways to return JSON data, depending on your version.

Let’s walk through two clear examples:

Example :1

In this example, we use Django >= 1.7 with the JsonResponse class from django.http. This is the recommended way in modern Django versions. If your object is not a dictionary, set safe=False.

views.py
from django.http import JsonResponse

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

return JsonResponse(responseData)
Example :2

This method is for Django versions < 1.7. We use HttpResponse along with json.dumps and explicitly set the content type to application/json.

views.py
import json
from django.http import HttpResponse

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

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

I hope this helps you understand how to return JSON data in Django applications. Whether you're building a RESTful API or returning AJAX data, this is a fundamental technique.

Frequently Asked Questions (FAQs)

Q1: What is JsonResponse in Django?
JsonResponse is a subclass of HttpResponse that simplifies returning JSON-encoded responses. It automatically sets the content type to "application/json".

Q2: When should I use JsonResponse vs HttpResponse?
Use JsonResponse when working with JSON data in modern Django versions (>= 1.7). Use HttpResponse for backward compatibility or custom response types.

Q3: How do I return non-dict JSON with JsonResponse?
Set the parameter safe=False when returning lists or other JSON-serializable objects that are not dictionaries.

Q4: Can I return a JSON response with a custom status code?
Yes. You can pass a status parameter to either JsonResponse or HttpResponse. Example: JsonResponse(data, status=201).

Q5: Do I need to use Django REST framework for JSON responses?
No. Django itself supports JSON responses using JsonResponse or HttpResponse, but Django REST Framework (DRF) offers more advanced features for building full RESTful APIs.

Happy coding!