【问题标题】:workaround for python json <= 2.7 datetime serializer not workingpython json <= 2.7 datetime 序列化程序的解决方法不起作用
【发布时间】:2013-05-22 10:17:47
【问题描述】:

这有点复杂,但我会尽力解释。 我有一个名为Event 的类,它有两个属性:

self.timestamp= datetime.now()
self.data = this is a big dictionary

我将这个类的所有实例放入一个列表中,最后使用json.dumps() 将整个列表打印到一个文件中。 json.dumps(self.timeline, indent=4, default=json_handler) 我正在使用可以安装/修改库的 python 环境,并且我只能访问 python json

这是我处理日期时间的解决方法:

# workaround for python json <= 2.7 datetime serializer
def json_handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    elif isinstance(obj, event.Event):
        return {obj.__class__.__name__ : obj.data}
    else:
        raise TypeError("Unserializable object {} of type {}".format(obj, type(obj)))

在我注意到 json 不打印任何时间戳之前,一切似乎都运行良好。 这是为什么?发生了什么事?

【问题讨论】:

    标签: json serialization python-2.7


    【解决方案1】:

    当序列化程序遇到您的event.Event 类型时,您只是在序列化其data 属性,完全跳过timestamp。您还需要以某种方式返回时间戳。可能是这样的:

    def json_handler(obj):
        if hasattr(obj, 'isoformat'):
            return obj.isoformat()
        elif isinstance(obj, Event):
            attrs = dict(data=obj.data, timestamp=obj.timestamp)
            return {obj.__class__.__name__: attrs}
        else:
            raise TypeError("Unserializable object {} of type {}".format(obj, type(obj)))
    

    【讨论】:

    • 谢谢!我知道我也必须返回时间戳,但我不知道该怎么做。我会对此进行测试并通知您!
    猜你喜欢
    • 2012-11-04
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 2013-09-04
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    相关资源
    最近更新 更多