我用json.dumps
序列化SQLAlchemy映射对象。我希望我的对象'association proxy属性也能正确序列化。默认情况下,它们没有正确序列化,因此我必须编写一个特定的JSON编码器:
from sqlalchemy.ext.associationproxy import _AssociationList
class MyEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, _AssociationList):
return list(obj)
return JSONEncoder.default(self, obj)
这看起来不太好,因为我需要导入SQLAlchemy私有的_AssociationList
。
还有其他选择吗?
答案 0 :(得分:1)
不是检查_AssociationList特定类型,而是可以进行更通用的测试:是“喜欢”列表吗?然后将其序列化为列表! (鸭子打字,见Python: check if an object is a list or tuple (but not string))。
def is_sequence(arg):
return (not hasattr(arg, "strip") and
hasattr(arg, "__getitem__") or
hasattr(arg, "__iter__"))
class MyEncoder(JSONEncoder):
def default(self, obj):
if is_sequence(obj):
return list(obj)
return JSONEncoder.default(self, obj)
这会处理集合,元组,_AssociationLists并将自己列为列表!但不是字符串,整数等。