pythondjangopandasjsonresponseto-json

How do I return data from Pandas DataFrame to be returned by Django's JsonResponse?


The answer to this is probably something really simple, but after hours of searching, I really could not find it.

I am trying to return a JsonResponse using Django from a pandas dataframe. One of the many things I've tried is the following:

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import pandas as pd

@csrf_exempt
def do_request(request):
    result = pd.DataFrame({'bla':[1,2,3],'bla2':['a','b','c']}).to_json(orient='records')
    return JsonResponse(result, safe = False)

The below ends up returning:

"[{\"bla\":1,\"bla2\":\"a\"},{\"bla\":2,\"bla2\":\"b\"},{\"bla\":3,\"bla2\":\"c\"}]"

when in fact I want it to return:

'[{"bla":1,"bla2":"a"},{"bla":2,"bla2":"b"},{"bla":3,"bla2":"c"}]'


Solution

  • You need to pass python objects (dictionary or list for example) as JsonResponse data. But to_json return string. So try to parse it:

    import json
    
    @csrf_exempt
    def do_request(request):
        result = pd.DataFrame({'bla':[1,2,3],'bla2':['a','b','c']}).to_json(orient='records')
        return JsonResponse(json.loads(result), safe = False)