![](/img/trans.png)
[英]How can I configure an exception view in Pyramid for friendly error pages, but still pass errors through to a logger?
[英]How can I configure Pyramid's JSON encoding?
我正在尝试返回这样的函数:
@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\"}"
看起来字典是JSON编码的两次,相当于:
json.dumps(json.dumps({ "color" : "color", "message" : "message" }))
也许你的Python框架会自动对结果进行JSON编码? 试试这个:
def returnJSON(color, message=None):
return { "color" : "color", "message" : "message" }
编辑:
要使用以您希望的方式生成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))
然后你有一个'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)
除了其他优秀的答案,我想指出,如果你不希望你的视图函数返回的数据通过json.dumps传递,那么你不应该在视图配置中使用renderer =“json”: )
而不是
@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)
你可以使用
@view_config(route_name='CreateNewAccount', request_method='GET', renderer='string')
def returnJSON(color, message=None):
return json.dumps({ "color" : "color", "message" : "message" }, default=json_util.default)
string
renderer将只传递函数返回的字符串数据。 但是,注册自定义渲染器是一种更好的方法(请参阅@ orip的答案)
你没有说,但我会假设你只是使用标准的json
模块。
json
模块没有为JSON定义类; 它使用标准的Python dict
作为数据的“本机”表示。 json.dumps()
将dict
编码为JSON字符串; json.loads()
接受一个JSON字符串并返回一个dict
。
所以不要这样做:
def returnJSON(color, message=None):
return json.dumps({ "color" : "color", "message" : "message" }, default=json_util.default)
试着这样做:
def returnJSON(color, message=None):
return { "color" : "color", "message" : "message" }
只是传回一个简单的dict
。 了解您的iPhone应用程序是如何喜欢这样
json.dumps手册指出:
将obj序列化为JSON格式的str。
要从字符串转换回来,您需要使用Python JSON函数加载 ,将LOADS字符串加载到JSON对象中。
但是,你试图做的是将python字典encode
为JSON。
def returnJSON(color, message=None):
return json.encode({ "color" : color, "message" : message })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.