【问题标题】:Why is this class not JSon serializable? [duplicate]为什么这个类不是 JSON 可序列化的? [复制]
【发布时间】:2018-05-12 00:06:40
【问题描述】:

我在 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.

你们能帮我理解为什么吗? 我在这里很迷茫。

【问题讨论】:

    标签: python json


    【解决方案1】:

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

    【讨论】:

    • 成功了!我想知道为什么 Json 编码器不做这项工作并为它找到的每个对象调用 ._ dict _。
    • 如果我的回答对你有帮助,你可以点赞。
    猜你喜欢
    • 2010-12-27
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 2011-01-15
    • 2018-03-05
    • 2015-03-01
    相关资源
    最近更新 更多