为什么从django休息框架返回的JSON在响应中有斜杠? [英] Why does JSON returned from the django rest framework have forward slashes in the response?

查看:381
本文介绍了为什么从django休息框架返回的JSON在响应中有斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的回复代码

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

出现在 curl 或通过浏览器访问响应。

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

"{\"success\": true}"

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

Why the forward slashes? How do I remove them?

推荐答案

您将数据呈现为JSON 两次。删除您的 json.dumps()调用。

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

Django REST文档


与常规 HttpResponse 对象不同,您不会实例化具有渲染内容的 Response 对象。

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编码

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}"

该框架使用 内容谈判 来确定要使用的序列化格式;这样您的API客户端也可以请求数据被编码为YAML或XML,例如。

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框架通过提供一个 Response 类来支持HTTP内容协商,该类允许您将可以呈现为多个内容类型的内容返回,具体取决于客户端请求。

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.

这篇关于为什么从django休息框架返回的JSON在响应中有斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆