为什么从 django rest 框架返回的 JSON 在响应中有正斜杠?

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

我的回复码

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

它在执行 curl 或通过浏览器访问响应时的显示方式。

"{\"success\": true}"

为什么是正斜杠?我如何删除它们?

您正在将数据呈现 JSON 两次 。删除您的 json.dumps() 通话。

来自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.

然后 Django REST 框架会为您生成 JSON。由于您给了它一个字符串,该字符串被 JSON 再次编码 :

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

框架使用Content Negotiation来决定使用什么序列化格式;这样,您的 API 客户也可以请求将数据编码为 YAML 或 XML,例如。

另见 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.