Django - Return a JSON-encoded response

Sep 30, 2017 Djnago 中文版

Django, probably the most popular Python web framework, provides users with various ways of returning different types of data (e.g. JSON, File) to client. If you search “How to return JSON-encoded response using Django”, it’s easy to get several different answers. Actually, Django gives us a simple way, so this post is about how to use it.


If you have not created a proper environment for the following steps, you can use below commands:

# Install Django
python -m pip install Django

# Check Django's version
python -m django --version

# Create a new Django project
django-admin startproject <project-name>

The structure of your project should look like this:

├── project-name
│   ├──
│   ├──
│   ├──
│   ├──

Use JsonResponse

Since version 1.7, Django has provided an object named JsonResponse. It’s default Content-Type is set as application/json, and it will serialize your data and return to client. Here is an example how to use it:

from django.http import JsonResponse
from django.views import View

class SandboxHandler(View):
    def get(self, request):
        data = {
            'name': 'Django',
            'version': '1.x'
        return JsonResponse(data)

The parameter you passed to JsonResponse should be dict type. Otherwise, Django will throw an error. If you want to pass non-dict type object, you can use option safe=False. Like this:

return JsonResponse(other_object, safe=False)

In addition to that, you can even use your own JSON encoder:

return JsonResponse(other_object, encoder=OtherJsonEncoder)

You might also like:

If you have any suggestions, questions or even find some typos, feel free to contact me. Thank you! :)   © 2015-2019 zeckli, thanks to Jekyll and GitHub.