0
0
DjangoHow-ToBeginner · 3 min read

How to Use JsonResponse in Django: Simple Guide

Use Django's JsonResponse to return JSON data from a view by passing a Python dictionary to it. It automatically converts the dictionary to JSON and sets the correct content type application/json for the response.
📐

Syntax

The basic syntax of JsonResponse is simple. You import it from django.http and return it from your view with a dictionary as the first argument.

  • data: A Python dictionary or list to convert to JSON.
  • safe: Boolean, default True. If True, only dict objects are allowed. Set to False to allow lists or other JSON-serializable objects.
  • json_dumps_params: Optional dictionary to customize JSON encoding.
python
from django.http import JsonResponse

def my_view(request):
    data = {'key': 'value'}
    return JsonResponse(data, safe=True)
💻

Example

This example shows a Django view that returns a JSON response with user info. It demonstrates passing a dictionary to JsonResponse and how the response looks in the browser or API client.

python
from django.http import JsonResponse

def user_info(request):
    user_data = {
        'username': 'alice',
        'age': 30,
        'active': True
    }
    return JsonResponse(user_data)
Output
{"username": "alice", "age": 30, "active": true}
⚠️

Common Pitfalls

Common mistakes when using JsonResponse include:

  • Passing a list or non-dict object without setting safe=False, which raises an error.
  • Not importing JsonResponse from django.http.
  • Trying to return non-serializable objects like Django models directly.

Always convert complex objects to dictionaries or lists before returning.

python
from django.http import JsonResponse

def wrong_view(request):
    data = ['apple', 'banana']
    # This will raise TypeError because safe=True by default
    # return JsonResponse(data)

    # Correct way:
    return JsonResponse(data, safe=False)
📊

Quick Reference

ParameterDescriptionDefault
dataPython dict or list to convert to JSONRequired
safeAllow only dict if True; set False for listsTrue
json_dumps_paramsCustomize JSON encoding (e.g., indent)None

Key Takeaways

Use JsonResponse to easily return JSON from Django views by passing a dictionary.
Set safe=False when returning lists or non-dict JSON data to avoid errors.
Always convert complex objects to serializable types before returning.
JsonResponse sets the correct content type and handles JSON encoding automatically.