gpt4 book ai didi

python - 如何配置 Pyramid 的 JSON 编码?

转载 作者:太空狗 更新时间:2023-10-29 22:16:36 26 4
gpt4 key购买 nike

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

@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)

由于 Pyramid 自己的 JSON 编码,它会像这样进行双重编码:

"{\"color\": \"color\", \"message\": \"message\"}"

我该如何解决这个问题?我需要使用 default argument (或等效项)因为它是 Mongo 的自定义类型所必需的。

最佳答案

字典似乎被 JSON 编码了两次,相当于:

json.dumps(json.dumps({ "color" : "color", "message" : "message" }))

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

def returnJSON(color, message=None):
return { "color" : "color", "message" : "message" }

编辑:

要使用自定义 Pyramid 渲染器以您想要的方式生成 JSON,请尝试这个(基于 renderer docsrenderer sources)。

启动时:

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

config = Configurator()
config.add_renderer('json_with_custom_default', JSON(default=json_util.default))

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

@view_config(route_name='CreateNewAccount', request_method='GET', renderer='json_with_custom_default')

编辑 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)

关于python - 如何配置 Pyramid 的 JSON 编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10887324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com