0

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"}]'

Shooth
  • 83
  • 2
  • 10

1 Answers1

6

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)
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • 1
    This has been very helpful. I was missing the "json.loads()" call in my JsonResponse(), and the result kept coming as a string. Thanks! – Shanti Dec 24 '20 at 03:40