我是python的新手,我尝试序列化自定义对象的列表。这是我尝试序列化的对象:
test = [(deliveryRecipientObject){
deliveryType = "selected"
id = "gkfhgjhfjhgjghkj"
type = "list"
}]
阅读了一些帖子和教程后,我想到了这个:
class deliverRecipientObject(object):
def __init__(self):
self.deliveryType = ""
self.id = ""
self.type = ""
class MyJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, deliverRecipientObject):
return {}
return (MyJsonEncoder, self).dumps(obj)
然后我跑步:
json.dumps(test, cls=MyJsonEncoder)
然后我收到此错误:AttributeError:'tuple'对象没有属性'dumps'
我的目标是将其读取为json,然后可以将其展平并另存为csv
谢谢
我认为您可能希望(MyJsonEncoder, self).dumps
为super(MyJsonEncoder, self).dumps
,尽管那也将是错误的。相反,您应该调用super().default
(在python 3中,您不需要传递参数)
class MyJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, deliverRecipientObject):
return {
"deliveryType": obj.deliveryType,
"id": obj.id,
"type": obj.type,
}
return super().default(obj)