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.