Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data from JsonResponse in django

Tags:

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

like image 214
Mattia Carolo Avatar asked Sep 18 '19 09:09

Mattia Carolo


People also ask

What does JsonResponse do in Django?

An HttpResponse subclass that helps to create a JSON-encoded response. It inherits most behavior from its superclass with some differences: Its default Content-Type header is set to application/json .

How do I return a JSON object in Django?

Returning a JSON response from a Django Model. To return a queryset of python object as JSON, we first have to convert it into a Python dictionary. The process of converting one data type to another is called serialization. We import the serialize function.

What is JsonResponse in python?

JsonResponse is an HttpResponse subclass that helps to create a JSON-encoded response. Its default Content-Type header is set to application/json. The first parameter, data , should be a dict instance.

What is HttpResponse in Django?

HttpResponse (source code) provides an inbound HTTP request to a Django web application with a text response. This class is most frequently used as a return object from a Django view.


1 Answers

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)
like image 136
Toni Sredanović Avatar answered Oct 19 '22 03:10

Toni Sredanović