我有一个类,长得像这样:
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
不可迭代,这是正确的。我该如何使方法返回我想要的JSON?
我知道我可以通过从我的Sound
对象中显式地创建一个字典来实现这一点,就像这样:
return jsonify({"name": s.name, "length": s.length})
但这种方法对我来说看起来很丑陋。有没有更好的方法实现我的目标?
dir()
和getattr()
)。 - Mark Hildreth