JSON response

linkaiyi
Follow

two way to return json response

return json string (already dumped)

import json
from django.http import HttpResponse

def profile(request):
    data = {
        'name': 'Vitor',
        'location': 'Finland',
        'is_active': True,
        'count': 28
    }
    dump = json.dumps(data)
    return HttpResponse(dump, content_type='application/json')

use JsonResponse

See a minimal example below:

from django.http import JsonResponse

def profile(request):
    data = {
        'name': 'Vitor',
        'location': 'Finland',
        'is_active': True,
        'count': 28
    }
    return JsonResponse(data)

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.

return JsonResponse([1, 2, 3, 4], safe=False)

See below the class signature:

class JsonResponse(data, encoder, safe, json_dumps_params, **kwargs)

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:

def get_users(request):
    users = User.objects.all().values('first_name', 'last_name')  # or simply .values() to get all fields
    users_list = list(users)  # important: convert the QuerySet to a list object
    return JsonResponse(users_list, safe=False)
Object has 0 attachments

Was this article helpful?

This article is viewed 42 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support