1

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

4

1 に答える 1

1

シリアライザーがタイプに遭遇すると、その属性を完全にスキップしてevent.Eventシリアライズするだけです。何らかの形でタイムスタンプも返す必要があります。たぶん次のようなもの:datatimestamp

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 に答える