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
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 .
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With