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

2024-03-28 22:07:23 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题中描述的问题是由一个愚蠢的错误引起的,这个错误是在我尝试修复它的方法时犯的,即在测试之后不恢复所做的更改--但是网站不允许我删除它。所以我建议你把时间花在别的地方,不要管它。

在尝试最初建议使用自定义子类解决打印问题的JSONEncoder时,我发现documentation建议在扩展JSONEncoder:部分中执行的操作似乎不起作用。这是我的代码,它是在文档的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)

这是追踪结果:

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

Tags: inpyselfjsonobjdefaultvalueline
1条回答
网友
1楼 · 发布于 2024-03-28 22:07:23

医生说:

To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

print json.dumps(data_structure, cls=MyEncoder)

收益率

{"layer1": {"layer2": {"layer3_2": "string", "layer3_1": "MyEncoder::NoIndent object"}}}

相关问题 更多 >