2012-11-06 79 views
4

在这个问题中描述的问题是由于我在尝试修复它的方法时犯的一个愚蠢的错误造成的,即在测试之后没有恢复所做的更改 - 但是该站点不允许我删除它。所以我建议你省去一些时间,让自己在别处忽略不计。为什么这个自定义json编码器不工作?

虽然尝试了answer最初使用自定义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 
+0

自我破坏(以这样的方式,以使它们失效他人编辑的问题)是违反网站规则。见ie。 http://meta.stackoverflow.com/questions/275864/anything-that-should-be-done-about-a-user-gutting-questions/275866#275866 –

回答

16

文档说:

要使用自定义JSONEncoder子类(如一个覆盖 默认()方法序列化附加类型),用 cls kwarg指定它;否则使用JSONEncoder。

print json.dumps(data_structure, cls=MyEncoder) 

产生

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

糟糕,我只注意到我自己:$。原本就是这样,但我在做一些试验的时候改变了它,忘了放回去。谢谢。 – martineau