11

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

2 Answers 2

12

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. I searched in the wrong part of the documentation xD
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: docs.djangoproject.com/en/2.2/ref/request-response/#id2
2

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 ?

1 Comment

I had to use json.loads(source.content.decode()) (so was missing the .content call to get the raw JSON

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.