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
.
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"')