Since version 1.7, Django counts with the built-in JsonResponse
class, which is a subclass of HttpResponse
.
Its default Content-Type header is set to application/json, which is really convenient. It also comes with a
JSON encoder, so you don’t need to serialize the data before returning the response object.
See a minimal example below:
By default, the JsonResponse
’s first parameter, data, should be a dict instance. To pass any other
JSON-serializable object you must set the safe parameter to False.
See below the class signature:
Defaults:
- data: (no default)
- encoder: django.core.serializers.json.DjangoJSONEncoder
- safe: True
- json_dumps_params: None
Extra bits:
If you want to return Django models as JSON, you may want to it this way:
Troubleshooting
Django 1.6 or below
For older versions of Django, you must use an HttpResponse
object. See an example below:
Leave a comment below if this article was helpful to you! Or if you have any questions/suggestions/improvements etc etc please let me know! :-)
You can also subscribe to my mailing list. I send exclusive content every week!