Creating a JSON response using Django and Python

Gareth D.

The Problem

You want to pass a JSON response from your Django backend to use with AJAX or a frontend web framework.

The Solution

Django (since version 1.7) provides a JsonResponse object which converts a Python dictionary into JSON. It also works with other Python data structures, such as arrays, but if you’re using anything that’s not a dictionary you need to explicitly set safe=False. In this case, you should also be careful that your application isn’t ever going to return more or different data to the frontend than you expect.

In your views.py file, you can return JSON as demonstrated in the following code. The first view uses a simple dictionary, while the second one returns an array, so we set safe=False.

Click to Copy
from django.http import JsonResponse def index(request): my_dictionary = {"a": 1, "b": 2} return JsonResponse(my_dictionary) def index2(request): my_array = [("a", 1), ("b", 2)] return JsonResponse(my_array, safe=False)

The index function above will return {"a": 1, "b": 2} while index2 will return [["a", 1], ["b", 2]] (note the round brackets are converted to square brackets to conform with standard JSON).

Serialization and escaping

If you use JsonResponse to return an entire object, Django will escape the double quotation marks in all fields. For example, if you have the following object:

Click to Copy
from django.core import serializers from django.http import JsonResponse from django.db import models class MyTrickyObject(models.Model): quotes = models.CharField(max_length=100) def index(request): MyTrickyObject.objects.all().delete() all_objs = MyTrickyObject.objects.all() tricky_obj = MyTrickyObject(quotes='"this is a quoted string"') tricky_obj.save() tricky_objects = MyTrickyObject.objects.all() data = serializers.serialize('json', all_objs) return JsonResponse(data, safe=False)

Then the response will be:

Click to Copy
"[{\"model\": \"sandboxapp.mytrickyobject\", \"pk\": 21, \"fields\": {\"quotes\": \"\\\"this is a quoted string\\\"\"}}]"

Note how every field includes the (escaped) double quotes, and the actual quotes in the quotes field are now double escaped. Instead, you can use an HttpResponse and content_type='application/json' to get just the fields without the quotes:

Click to Copy
from django.core import serializers from django.http import HttpResponse from django.db import models class MyTrickyObject(models.Model): quotes = models.CharField(max_length=100) def index(request): MyTrickyObject.objects.all().delete() all_objs = MyTrickyObject.objects.all() tricky_obj = MyTrickyObject(quotes='"this is a quoted string"') tricky_obj.save() tricky_objects = MyTrickyObject.objects.all() data = serializers.serialize('json', all_objs) return HttpResponse(data, content_type='application/json')

Now the response will be:

Click to Copy
[{"model": "sandboxapp.mytrickyobject", "pk": 22, "fields": {"quotes": "\"this is a quoted string\""}}]

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.