1

这有点复杂,但我会尽力解释。我有一个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 <= 2.7。

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

# 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 没有打印任何时间戳。这是为什么?怎么了?

4

1 回答 1

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)))
于 2013-05-27T19:53:31.760 回答