6

この質問で説明されている問題は、修正方法を試しているときに行ったばかげた間違い、つまりテスト後に行った変更を元に戻さないことが原因でした。ただし、サイトでは削除できません。ですから、無視することで、他の場所で過ごす時間を節約することをお勧めします。

印刷の問題を解決するためにカスタムサブクラスを使用することを最初に提案した回答を試しているときに、ドキュメントがJSONEncoderの拡張:セクションで行うことを提案していることが機能していないように見えることを発見しました。これは、ドキュメントのそのセクションにもある例に基づいてパターン化された私のコードです。JSONEncoderComplexEncoder

import json

class NoIndent(object):
    def __init__(self, value):
        self.value = value

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        print 'MyEncoder.default() called'
        if isinstance(obj, NoIndent):
            return 'MyEncoder::NoIndent object'  # hard code string for now
        else:
            return json.JSONEncoder.default(self, obj)

data_structure = {
    'layer1': {
        'layer2': {
            'layer3_1': NoIndent([{"x":1,"y":7},{"x":0,"y":4},{"x":5,"y":3},{"x":6,"y":9}]),
            'layer3_2': 'string'
        }
    }
}

print json.dumps(data_structure, default=MyEncoder)

そして、これが結果のトレースバックです。

Traceback (most recent call last):
  File "C:\Files\PythonLib\Stack Overflow\json_parsing.py", line 26, in <module>
    print json.dumps(data_structure, default=MyEncoder)
  File "E:\Program Files\Python\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "E:\Program Files\Python\lib\json\encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "E:\Program Files\Python\lib\json\encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
RuntimeError: maximum recursion depth exceeded
4

1 に答える 1

20

ドキュメントによると:

カスタムJSONEncoderサブクラス(たとえば、default()メソッドをオーバーライドして追加の型をシリアル化するサブクラス)を使用するには、clskwargで指定し ます。それ以外の場合は、JSONEncoderが使用されます。

print json.dumps(data_structure, cls=MyEncoder)

収量

{"layer1": {"layer2": {"layer3_2": "string", "layer3_1": "MyEncoder::NoIndent object"}}}
于 2012-11-06T13:13:24.827 に答える