【发布时间】: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