JSON in Django — JsonResponse, DRF Serializers, and Model JSON Fields
Django provides several layers for working with JSON: the built-in JsonResponse class for simple views, json.loads() for parsing request bodies, Django REST Framework (DRF) for full API development, and JSONField for storing JSON directly in the database.
Returning JSON with JsonResponse
Django's JsonResponse serialises a dict to JSON and sets the correct Content-Type header. It's the simplest way to return JSON from a view.
from django.http import JsonResponse
def user_list(request):
users = [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"},
]
return JsonResponse(users, safe=False)
# safe=False required for lists (default only allows dicts)
def user_detail(request, user_id):
user = {"id": user_id, "name": "Alice", "email": "alice@example.com"}
return JsonResponse(user, status=200)Parsing JSON request bodies
For POST/PUT requests with a JSON body, read request.body and parse it with json.loads(). Always validate the parsed data before use.
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt # use CSRF tokens in production instead
def create_user(request):
if request.method != "POST":
return JsonResponse({"error": "Method not allowed"}, status=405)
try:
data = json.loads(request.body)
except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON"}, status=400)
name = data.get("name")
if not name:
return JsonResponse({"error": "name is required"}, status=422)
return JsonResponse({"id": 1, "name": name}, status=201)Django REST Framework: Serializers and APIView
DRF is the standard library for building REST APIs in Django. Serializers validate and transform data; APIView provides method-based dispatch.
# serializers.py
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(max_length=100)
email = serializers.EmailField()
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class UserListView(APIView):
def get(self, request):
users = [{"id": 1, "name": "Alice", "email": "alice@example.com"}]
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
def post(self, request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)JSONField in models (Django 3.1+)
Store arbitrary JSON in a PostgreSQL, MySQL, or SQLite column using Django's built-in JSONField. Query into nested keys using the __ double-underscore lookup syntax.
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=200)
metadata = models.JSONField(default=dict, blank=True)
# Storing JSON
product = Product.objects.create(
name="Widget",
metadata={"color": "blue", "tags": ["sale", "featured"]},
)
# Querying by nested key (PostgreSQL / MySQL / SQLite)
blue_products = Product.objects.filter(metadata__color="blue")
sale_products = Product.objects.filter(metadata__tags__contains="sale")Custom JSON encoder for datetime and Decimal
Django's DjangoJSONEncoder handles datetime and Decimal out of the box. Pass it to JsonResponse or json.dumps() when you need to serialise these types.
from django.core.serializers.json import DjangoJSONEncoder
from django.http import JsonResponse
from datetime import datetime
from decimal import Decimal
def product_detail(request, pk):
data = {
"id": pk,
"price": Decimal("19.99"),
"created_at": datetime.now(),
}
# DjangoJSONEncoder handles Decimal → float and datetime → ISO string
return JsonResponse(data, encoder=DjangoJSONEncoder)
# Or with json.dumps:
import json
output = json.dumps(data, cls=DjangoJSONEncoder)Related Tools
Frequently Asked Questions
How do I return JSON from a Django view?▾
Use JsonResponse(data) from django.http. It serialises a dict to JSON and sets Content-Type: application/json. Pass safe=False to serialise lists or non-dict values.
How do I parse a JSON request body in Django?▾
Read request.body and call json.loads(request.body). Wrap it in a try/except for json.JSONDecodeError to handle malformed input. For DRF views, use request.data which is already parsed.
What is Django REST Framework and when should I use it?▾
Django REST Framework (DRF) is a third-party library that adds serializers, authentication, permissions, and viewsets on top of Django. Use it when building a full REST API. For simple one-off JSON endpoints, plain JsonResponse is sufficient.
How do I store JSON in a Django model?▾
Use models.JSONField() (available since Django 3.1 for PostgreSQL, MySQL, and SQLite). Assign any Python dict, list, or primitive to the field. Django handles serialisation and deserialisation automatically.
How do I serialise datetime and Decimal to JSON in Django?▾
Pass encoder=DjangoJSONEncoder to JsonResponse or json.dumps(). DjangoJSONEncoder converts datetime to an ISO 8601 string and Decimal to a float string. For DRF, these are handled automatically by the default renderer.
JSON in Other Languages
Format and validate your JSON instantly
Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.
Open JSON Formatter →If jsondecode.com saved you time, share it with your team
Free forever. No ads. No sign-up. Help other developers find it.