0
0
Djangoframework~5 mins

Returning JSON with JsonResponse in Django

Choose your learning style9 modes available
Introduction

JsonResponse helps you send data from your Django app to the browser in a simple way. It turns Python data into JSON format automatically.

When you want to send data to a web page without reloading it, like updating a list or showing new info.
When building APIs that other apps or websites can use to get data from your Django app.
When you want to respond to a form submission with data instead of a new page.
When you need to send status messages or small data packets to JavaScript running in the browser.
Syntax
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.

Examples
Sends a simple JSON object with a greeting message.
Django
from django.http import JsonResponse

def my_view(request):
    data = {'message': 'Hello, world!'}
    return JsonResponse(data)
Sends a JSON list by setting safe=False because lists are not allowed by default.
Django
from django.http import JsonResponse

def my_view(request):
    data = ['apple', 'banana', 'cherry']
    return JsonResponse(data, safe=False)
Sends the current time as a string in JSON format.
Django
from django.http import JsonResponse
import datetime

def my_view(request):
    data = {'time': datetime.datetime.now().isoformat()}
    return JsonResponse(data)
Sample Program

This Django view sends a JSON response with a greeting message when you visit the URL /greet/.

Django
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),
]
OutputSuccess
Important Notes

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.

Summary

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.