Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSON returned from the django rest framework have forward slashes in the response?

My response code

from rest_framework.response import Response
import json
responseData = { 'success' : True }
return Response(json.dumps(responseData))

How it appears on doing curl or accessing the response through the browser.

"{\"success\": true}"

Why the forward slashes? How do I remove them?

like image 942
Sai Krishna Avatar asked Jan 31 '15 07:01

Sai Krishna


People also ask

Why are there slashes in JSON?

Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON. parse to parse that JSON string into a JSON object.

How do you remove forward slash in JSON Python?

How do you escape a forward slash in JSON? Backspace to be replaced with \b. Form feed to be replaced with \f. Newline to be replaced with \n.

How do I return a JSON response in Django?

The JsonResponse transforms the data you pass to it to a JSON string and sets the content type HTTP header to application/json . To return JSON data from a Django view you swap out the HttpResponse for JsonResponse and pass it the data that needs to be transformed to JSON.

How do I remove backslash from JSON response in Python?

Using replace() Function Along with The json. Loads() Function to Remove Backslash from Json String in Python.


1 Answers

You are rendering the data to JSON twice. Remove your json.dumps() call.

From the Django REST documentation:

Unlike regular HttpResponse objects, you do not instantiate Response objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives.

The Django REST framework then takes care of producing JSON for you. Since you gave it a string, that string was JSON encoded again:

>>> import json
>>> responseData = { 'success' : True }
>>> print json.dumps(responseData)
{"success": true}
>>> print json.dumps(json.dumps(responseData))
"{\"success\": true}"

The framework uses Content Negotiation to determine what serialisation format to use; that way your API clients can also request that the data is encoded as YAML or XML, for example.

Also see the Responses documentation:

REST framework supports HTTP content negotiation by providing a Response class which allows you to return content that can be rendered into multiple content types, depending on the client request.

like image 128
Martijn Pieters Avatar answered Sep 17 '22 00:09

Martijn Pieters