JsonResponse helps you send data from your Django app to the browser in a simple way. It turns Python data into JSON format automatically.
Returning JSON with JsonResponse in Django
from django.http import JsonResponse def my_view(request): return JsonResponse(data, safe=True, json_dumps_params=None)
data is usually a Python dictionary or list that you want to send as JSON.
The safe parameter defaults to True, which means only dictionaries are allowed unless you set it to False.
from django.http import JsonResponse def my_view(request): data = {'message': 'Hello, world!'} return JsonResponse(data)
safe=False because lists are not allowed by default.from django.http import JsonResponse def my_view(request): data = ['apple', 'banana', 'cherry'] return JsonResponse(data, safe=False)
from django.http import JsonResponse import datetime def my_view(request): data = {'time': datetime.datetime.now().isoformat()} return JsonResponse(data)
This Django view sends a JSON response with a greeting message when you visit the URL /greet/.
from django.http import JsonResponse from django.urls import path # Simple view that returns JSON data def greet_view(request): data = {'greeting': 'Hello from Django!'} return JsonResponse(data) # URL patterns for Django urlpatterns = [ path('greet/', greet_view), ]
Always use JsonResponse instead of manually creating HTTP responses with JSON strings. It handles content type and encoding for you.
Remember to set safe=False if you want to return a list or other non-dictionary JSON data.
Use json_dumps_params to customize JSON formatting, like indentation for easier reading during development.
JsonResponse makes sending JSON data from Django easy and safe.
Use it to send dictionaries by default, or set safe=False for lists.
It automatically sets the right headers so browsers and clients know the response is JSON.