Mattia Carolo
Mattia Carolo

Reputation: 153

Get data from JsonResponse in django

I wanted to know how to get data from a JsonResponse in django. I made a JsonResponse that works like this

def pfmdetail(rsid):
   snpid = parseSet(rsid)
   if not snpid:
      return HttpResponse(status=404)
   try:
      data = SnpsPfm.objects.values('start', 'strand', 'type', 'scoreref', 'scorealt', 
                    rsid=F('snpid__rsid'), pfm_name=F('pfmid__name')).filter(snpid=snpid[0])
   except SnpsPfm.DoesNotExist:
      return HttpResponse(status=404)
   serializer = SnpsPfmSerializer(data, many=True)
   return JsonResponse(serializer.data, safe=False)

and then I call directly the method like this

def pfmTable(qset,detail):
   source = pfmdetail(detail)
   print(source)
   df = pd.read_json(source)

but it gives me an error. I know it's wrong because with the print it returns the status of the response which is 200 so I suppose that the response is fine but how can I access the data inside the response? I tried import json to do json.load but with no success. I even tried the methods of QueryDict but stil I can't acess to the content I'm interested

P.S. I know that data contains something because if i display the jsonresponse on the browser i can see the JSON

Upvotes: 10

Views: 10196

Answers (2)

Patricia Green
Patricia Green

Reputation: 523

If you aren't using pandas, then you should process the content attribute of the JSONResponse object like this:

r = json.loads(source.decode())

I got the answer here: How to parse binary string to dict ?

Upvotes: 2

Toni Sredanović
Toni Sredanović

Reputation: 2392

As you can see here: https://docs.djangoproject.com/en/2.2/ref/request-response/#jsonresponse-objects.

JsonResponse object holds json in its content attribute.

So to access it try this:

df = pd.read_json(source.content)

Or to see it printed do:

print(source.content)

Upvotes: 12

Related Questions