我有一节课看起来像是:
class Sound(SoundJsonSerializer):
def __init__(self, name, length):
self.name = name
self.length = length
其中SoundJsonSerializer允许我的自定义JSONEncoder将此对象序列化为JSON:
{
"name": "foobar",
"length": 23.4
}
现在我想让我的一个请求正好用上面的JSON响应。
@app.route('/sounds/<soundid>')
def get_sound(soundid):
s = Sound("foobar", 23.4)
return jsonify(s)
产生一个错误,声明s
不可iterable,这是真的。如何使方法返回所需的JSON?
我知道我可以通过显式地从我的Sound
对象创建dict来实现这一点,如下所示:
return jsonify({"name": s.name, "length": s.length})
但这对我来说真的很难看。实现目标的首选方法是什么?
目前没有回答
相关问题 更多 >
编程相关推荐