Thinker
Thinker

Reputation: 5356

Django list of json objects

I have a django backend and from my view I want to return a list of json objects.

@api_view(('GET',))
def get_analytics(request):
    # Number of users who dogged in once to our system today
    login_count=  User.objects.filter(last_login__startswith=
        timezone.now().date()).count() # returns int
    finished_count = Exercise_state.objects.filter(exercise_id=7, progress=2).count()
    # returns int

    count_list=[]
    count_list.append(login_count)
    count_list.append(finished_count)

    data = {}
    data['login_count'] = login_count
    data['finish_count'] = finished_count
    json_data = json.dumps(data)

    return Response(json_data)

This returns "{\"finish_count\": 1, \"login_count\": 2}" However what I want is something like [{"login_count": 2, "finished_count": 3}]

How can I achieve this?

Upvotes: 0

Views: 2095

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78546

Use JsonResponse instead, to properly parse the json object:

from django.http import JsonResponse

then, you can use your original dict object:

return JsonResponse(data) 

Upvotes: 1

Shang Wang
Shang Wang

Reputation: 25539

You need JsonResponse. But if you are going to use it you don't need json.dumps(data), JsonResponse dose it for you. Quoting from django doc:

>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'

If you are using django < 1.7, do(it's still available in later versions, but JsonResponse makes it eaiser):

return HttpResponse(json.dumps(data), content_type="application/json")

Upvotes: 2

Related Questions