为什么这个自定义json编码器不起作用?

mar*_*eau 5 python json

这个问题中描述的问题是由于我在尝试修复方法时犯了一个愚蠢的错误,即没有恢复测试后的更改 - 但是网站不允许我删除它.因此,我建议你通过忽略它来节省自己在别处花费的时间.

在尝试最初建议使用自定义子类来解决打印问题的答案时JSONEncoder,我发现文档建议在Extending JSONEncoder: section中执行的操作似乎不起作用.这是我的代码,该代码ComplexEncoder在文档的该部分的示例之后进行了模式化.

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)
Run Code Online (Sandbox Code Playgroud)

这是导致的追溯:

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
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 18

文档说:

要使用自定义JSONEncoder子类(例如,重写default()方法以序列化其他类型),请使用cls kwarg指定它 ; 否则使用JSONEncoder.

print json.dumps(data_structure, cls=MyEncoder)
Run Code Online (Sandbox Code Playgroud)

产量

{"layer1": {"layer2": {"layer3_2": "string", "layer3_1": "MyEncoder::NoIndent object"}}}
Run Code Online (Sandbox Code Playgroud)