【问题标题】:Why doesn't this custom json encoder work? [closed]为什么这个自定义 json 编码器不起作用? [关闭]
【发布时间】:2012-11-06 13:10:18
【问题描述】:

这个问题中描述的问题是由我在尝试修复它的方法时犯的一个愚蠢的错误引起的,即在测试后不恢复所做的更改——但是网站不允许我这样做删除它。所以我建议你忽略它,为自己节省一些更好地花在其他地方的时间。

在尝试最初建议使用自定义 JSONEncoder 子类来解决打印问题的 answer 时,我发现 documentation 建议在 Extending 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

【问题讨论】:

    标签: python json


    【解决方案1】:

    文档说:

    使用自定义 JSONEncoder 子类(例如,覆盖 default() 方法来序列化其他类型),用 cls kwarg;否则使用 JSONEncoder。

    print json.dumps(data_structure, cls=MyEncoder)
    

    产量

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

    【讨论】:

    • 糟糕,我刚刚注意到自己:$。原来是这样的,但我在做一些实验时改变了它,忘了把它放回去。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 2017-08-22
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 2017-12-13
    相关资源
    最近更新 更多