9

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

Mattia Carolo
  • 143
  • 1
  • 7

2 Answers2

11

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)
Toni Sredanović
  • 2,280
  • 1
  • 11
  • 13
  • Thanks a lot. I searched in the wrong part of the documentation xD – Mattia Carolo Sep 18 '19 at 09:56
  • 1
    Not a problem, two most important attributes of the djangos response objects are `status_code` and `content`. But there are more, to get more familiar with them see this: https://docs.djangoproject.com/en/2.2/ref/request-response/#id2 – Toni Sredanović Sep 18 '19 at 10:00
1

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 ?

Patricia Green
  • 495
  • 5
  • 14