如何配置Pyramid的JSON编码?

zak*_*ces 6 python json pymongo pyramid

我正在尝试返回这样的函数:

@view_config(route_name='CreateNewAccount', request_method='GET', renderer='json')
def returnJSON(color, message=None):
    return  json.dumps({ "color" : "color", "message" : "message" }, default=json_util.default)
Run Code Online (Sandbox Code Playgroud)

由于Pyramid自己的JSON编码,它出现了双重编码,如下所示:

"{\"color\": \"color\", \"message\": \"message\"}"
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?我需要使用default参数(或等价物),因为它是Mongo的自定义类型所必需的.

ori*_*rip 8

看起来字典是JSON编码的两次,相当于:

json.dumps(json.dumps({ "color" : "color", "message" : "message" }))
Run Code Online (Sandbox Code Playgroud)

也许你的Python框架会自动对结果进行JSON编码?试试这个:

def returnJSON(color, message=None):
  return { "color" : "color", "message" : "message" }
Run Code Online (Sandbox Code Playgroud)

编辑:

要使用以您希望的方式生成JSON的自定义Pyramid渲染器,请尝试此操作(基于渲染器文档渲染器源).

在启动时:

from pyramid.config import Configurator
from pyramid.renderers import JSON

config = Configurator()
config.add_renderer('json_with_custom_default', JSON(default=json_util.default))
Run Code Online (Sandbox Code Playgroud)

然后你有一个'json_with_custom_default'渲染器使用:

@view_config(route_name='CreateNewAccount', request_method='GET', renderer='json_with_custom_default')
Run Code Online (Sandbox Code Playgroud)

编辑2

另一种选择可能是返回Response渲染器不应修改的对象.例如

from pyramid.response import Response
def returnJSON(color, message):
  json_string = json.dumps({"color": color, "message": message}, default=json_util.default)
  return Response(json_string)
Run Code Online (Sandbox Code Playgroud)

  • 您使用的是哪个Python Web框架?您需要禁用自动JSON编码,或找到一种方法来修改框架执行JSON编码的方式. (2认同)