为什么这个类不是JSon可序列化的?

时间:2017-11-28 13:48:56

标签: python json

我在Python 3.5中有这个类:

class DataPoint(object):

    def __init__(self, time, value):
        self.time = time
        self.value = value

当我尝试从实例创建一个JSon时,执行:

json.dumps( intance_of_datapoint )

我收到错误:

TypeError: < DataPoint object at 0x0123 > is not JSon Serializable

所以我试图改进课程覆盖 repr 方法,如下所示:

class DataPoint(object):

    def __init__(self, time, value):
        self.time = time
        self.value = value

    def __str__(self):
        return json.dumps(self.__dict__)

    __repr__ = __str__

通过这样做我得到:

TypeError: {"value":52.29, "time":1} is not JSon serializable.

你们能帮我解决原因吗? 我在这里很丢失。

1 个答案:

答案 0 :(得分:2)

您需要在python dict中转换您的实例,然后您可以将该dict转储到json.dumps(instance_dict)中。因为,由于json有自己的数据类型,而python用户定义的类无法序列化为json。

相关问题