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.
Practice
JsonResponse class?Solution
Step 1: Understand JsonResponse role
JsonResponse is designed to send JSON data back to the client as an HTTP response.Step 2: Differentiate from other JSON tasks
It does not parse incoming JSON or render HTML; it only sends JSON safely with correct headers.Final Answer:
To send JSON data as an HTTP response easily and safely -> Option AQuick Check:
JsonResponse sends JSON response [OK]
- Confusing JsonResponse with JSON parsing
- Thinking it renders HTML templates
- Assuming it converts JSON strings to dicts
{"name": "Alice"} using JsonResponse?Solution
Step 1: Use JsonResponse with a dictionary
JsonResponse accepts a dictionary by default and sets safe=True, so no extra argument is needed.Step 2: Differentiate correct usage
Passing a list of dictionaries produces a JSON array instead of a single object; passing JSON strings causes TypeError.Final Answer:
return JsonResponse({"name": "Alice"}) -> Option BQuick Check:
Dict input with default safe=True [OK]
- Passing JSON string instead of dict
- Passing a list produces JSON array instead of object
- Using json.dumps inside JsonResponse
from django.http import JsonResponse
def my_view(request):
data = [1, 2, 3]
return JsonResponse(data, safe=False)Solution
Step 1: Recognize safe=False allows list data
JsonResponse by default requires dict; safe=False allows lists like [1, 2, 3].Step 2: Understand output JSON content
The response will contain the JSON array [1, 2, 3] as the body with correct headers.Final Answer:
HTTP response with JSON array [1, 2, 3] -> Option AQuick Check:
safe=False lets list output [OK]
- Omitting safe=False causes TypeError
- Expecting JSON object instead of array
- Confusing JSON string with JSON array
from django.http import JsonResponse
def my_view(request):
data = ["apple", "banana"]
return JsonResponse(data)Solution
Step 1: Check data type passed to JsonResponse
Data is a list, but JsonResponse defaults to safe=True, which only allows dicts.Step 2: Understand error cause
Without safe=False, passing a list raises TypeError because it's unsafe to send raw lists.Final Answer:
Missing safe=False causes TypeError for list data -> Option DQuick Check:
List needs safe=False to avoid error [OK]
- Forgetting safe=False with lists
- Trying to json.dumps before JsonResponse
- Assuming JsonResponse accepts lists by default
["Alice", "Bob"] from a Django view. Which is the correct way to do this?Solution
Step 1: Decide JSON structure to return
Returning a list directly requires safe=False because JsonResponse defaults to safe=True (dict only).Step 2: Avoid common mistakes
Passing safe=True with a list causes error; json.dumps returns string, which JsonResponse does not accept.Final Answer:
return JsonResponse(["Alice", "Bob"], safe=False) -> Option CQuick Check:
List with safe=False returns JSON array [OK]
- Setting safe=True with list causes error
- Passing JSON string instead of Python list
- Wrapping list inside dict unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
