How to Return JSON from a View in Django: Simple Guide
In Django, you can return JSON from a view by using the
JsonResponse class from django.http. Simply pass a Python dictionary to JsonResponse, and it will convert it to JSON and set the correct content type automatically.Syntax
The basic syntax to return JSON from a Django view uses the JsonResponse class. You import it from django.http and return it with a dictionary as the data.
- JsonResponse(data, safe=True): Converts
data(usually a dictionary) to JSON. - safe=True: Ensures only dictionaries are accepted by default for security.
python
from django.http import JsonResponse def my_view(request): data = {'key': 'value'} return JsonResponse(data)
Example
This example shows a complete Django view that returns JSON data with a message and a status code. When you visit this view in a browser or API client, it sends JSON with the correct content type.
python
from django.http import JsonResponse def hello_json(request): response_data = { 'message': 'Hello, JSON from Django!', 'status': 200 } return JsonResponse(response_data)
Output
{"message": "Hello, JSON from Django!", "status": 200}
Common Pitfalls
Some common mistakes when returning JSON in Django views include:
- Passing a list or other non-dictionary type to
JsonResponsewithout settingsafe=False. By default,safe=Trueonly allows dictionaries. - Manually converting data to JSON with
json.dumpsand returningHttpResponsewithout setting thecontent_typetoapplication/json. - Forgetting to import
JsonResponsefromdjango.http.
Example of wrong and right ways:
python
from django.http import JsonResponse, HttpResponse import json def wrong_view(request): data = ['a', 'b', 'c'] # This will raise an error because safe=True by default # return JsonResponse(data) # Correct way for non-dict data: return JsonResponse(data, safe=False) def manual_json_view(request): data = {'key': 'value'} json_data = json.dumps(data) return HttpResponse(json_data, content_type='application/json')
Quick Reference
| Concept | Description |
|---|---|
| JsonResponse | Class to return JSON response with correct headers |
| safe=True | Allows only dict data by default for security |
| safe=False | Allows lists or other JSON-serializable types |
| content_type | Automatically set to 'application/json' by JsonResponse |
| Manual JSON | Use json.dumps + HttpResponse with content_type if needed |
Key Takeaways
Use JsonResponse to return JSON easily and correctly in Django views.
Pass a dictionary to JsonResponse or set safe=False for other data types.
Avoid manual JSON conversion unless you need custom behavior.
Always import JsonResponse from django.http.
JsonResponse sets the correct content type automatically.