AttributeError:“元组”对象没有属性“ dumps”

时间:2019-10-11 16:27:16

标签: json python-3.7

我是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

谢谢

1 个答案:

答案 0 :(得分:0)

我认为您可能打算将(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)