これは少し複雑ですが、できる限り説明したいと思います。Event
私は2つの属性で呼び出されるクラスを持っています:
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がタイムスタンプを出力しないことに気付くまで、すべてが正常に機能しているように見えました。何故ですか?何が起こっている?