How can I get Django to return JsonResponse without extra quotes or quotes?

Using Django 1.7 when I return the following JsonResponse bit in a view:

from django.http import JsonResponse token = "1$aEJUhbdpO3cNrXUmFgvuR2SkXTP9=" response = JsonResponse({"token": token}) return response 

I get the following HTTP response from the / cURL web browser:

 "{\"token\": \"1$aEJUhbdpO3cNrXUmFgvuR2SkXTP9=\"}" 

What I want and what I had in Django 1.3 was the following:

 {"token": "1$aEJUhbdpO3cNrXUmFgvuR2SkXTP9="} 

I have two mobile apps in production that rely on a private API using Django, and unfortunately they expect a second type of response, without extra quotes (a quote that surrounds all JSON, making it a string), and no quote escapes.

My question is: is there any built-in way to get Django to respond so as not to escape the JSON response?

I wrote the following middleware to do this, but ... this seems like a really fragile way to iterate over:

 class UnescapeJSON(object): def process_response(self, request, response): """ Directly edit response object here, searching for and replacing terms in the html. """ if re.search('^/api/.*', request.path): r = response.content r = r.replace('\\', '') r = r.lstrip('"') r = r.rstrip('"') response.content = r return response 

So, I hope there is a smarter way.

Backstory - I am trying to upgrade an outdated code base from Django 1.3 to 1.8. I am currently using it in version 1.7 in a local environment. Django 1.3 returned JSON the correct path without extra quotes and backslashes.

One good thing about returning JSON this way:

 {"token": "1$aEJUhbdpO3cNrXUmFgvuR2SkXTP9="} 

... is that I use jQuery.post({success:...}) to handle this JSON response, and it automatically runs jQuery.parseJSON() for me, turning it into a JSON object to which I can access with dotted notation.

I can't just fix the line on the client side and re-run parseJSON() manually, because it will require all my users to update their mobile application.

So, I need to format JSON as above, or my mobile API is effectively broken.

One bit of information I have to add. This API uses Django Piston :( I am using the 1.7x compatible version that I found. It is not in my pockets to exchange in the Django REST Framework right now. Believe me, I will as soon as possible.

+5
source share
2 answers

I saw this with the Django REST Framework in a 1.8 deployment. I recently moved from 1.3 to 1.8. However, I did not have RESTful support up to 1.8, so I cannot claim that this ever worked (or did not work).

The problem was caused by the fact that I created Python dictionaries, serialized them for JSON objects, and then called json.dumps () as a result. The final step, which called json.dumps () and passed the result to the Response () constructor, caused the string to be wrapped in double quotes.

Change my code:

 def get(self, request, year, month, day, format=None): resp = None date = datetime(int(year), int(month), int(day), 0, 0) clinics = Clinic.objects.all() for x in clinics: aDate = datetime(x.date.year, x.date.month, x.date.day) if date >= aDate and date <= aDate + timedelta(days=x.duration): resp = serializers.serialize("json", [x, ]) struct = json.loads(resp) struct[0]["fields"]["id"] = x.id resp = json.dumps(struct[0]["fields"]) break if resp == None: raise NotFound() return Response(resp) 

to

 def get(self, request, year, month, day, format=None): resp = None date = datetime(int(year), int(month), int(day), 0, 0) clinics = Clinic.objects.all() for x in clinics: aDate = datetime(x.date.year, x.date.month, x.date.day) if date >= aDate and date <= aDate + timedelta(days=x.duration): resp = serializers.serialize("json", [x, ]) struct = json.loads(resp) struct[0]["fields"]["id"] = x.id resp = struct[0]["fields"] break if resp == None: raise NotFound() return Response(resp) 

fixed problem (for me) in Django REST. (Note that the line I'm assigning resp to is the only one that needs to be changed). Hope this helps somehow.

+2
source

For those who find this topic on Google, cut out JsonResponse. If you try to use jsonp, you will get an error

"TypeError: to enable serialization of non-dictical objects, set the safe parameter to False"

If you set Secure False, you will receive a response sent back with quotes around it, which will then fail on the client side. Instead

 return HttpResponse(response_data, content_type='application/json') 
-1
source

All Articles