为什么这个自定义json编码器不起作用? [英] Why doesn't this custom json encoder work?

查看:122
本文介绍了为什么这个自定义json编码器不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题中描述的问题是由于我在尝试解决该问题的方法时犯了一个愚蠢的错误而导致的,即不还原测试后所做的更改-但是该网站不允许我进行删除它.因此,我建议您通过忽略它来节省自己在其他地方花费的时间.

在尝试最初建议使用自定义JSONEncoder子类来解决打印问题的答案时,我发现文档表示在扩展JSONEncoder:部分似乎无法正常工作.这是我的代码,也是在文档的该部分中的ComplexEncoder示例之后构造的.

While trying out an answer that initially suggested using a custom JSONEncoder subclass to solve a printing problem, I discovered that what the documentation suggests doing in the Extending JSONEncoder: section does not appear to work. Here's my code which is patterned after the ComplexEncoder example also in that section of the docs.

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

推荐答案

文档说:

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

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"}}}

这篇关于为什么这个自定义json编码器不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆