class JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, **kwargs)
An HttpResponse
subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with some differences:
- Its default
Content-Type
header is set toapplication/json
. - The first parameter,
data
, should be adict
instance. If thesafe
parameter is set toFalse
(see below) it can be any JSON-serializable object. - The
encoder
, which defaults todjango.core.serializers.json.DjangoJSONEncoder
, will be used to serialize the data.
The safe
boolean parameter defaults to True
. If it's set to False
, any object can be passed for serialization (otherwise only dict
instances are allowed). If safe
is True
and a non-dict
object is passed as the first argument, a TypeError
will be raised.
Typical usage could look like:
>>> from django.http import JsonResponse >>> response = JsonResponse({'foo': 'bar'}) >>> response.content '{"foo": "bar"}'
Serializing non-dictionary objects
In order to serialize objects other than dict
you must set the safe
parameter to False
:
response = JsonResponse([1, 2, 3], safe=False)
Without passing safe=False
, a TypeError
will be raised.
Changing the default JSON encoder
If you need to use a different JSON encoder class, you can pass the encoder
parameter to the constructor method:
response = JsonResponse(data, encoder=MyJSONEncoder)