我有一个包含__hash__和__eq__方法的对象的Python集合,以确保集合中不包含重复的对象。
我需要json编码这个结果集,但传递甚至一个空集json。dumps方法引发TypeError。
File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: set([]) is not JSON serializable
我知道我可以为json创建一个扩展。JSONEncoder类,它有一个自定义的默认方法,但我甚至不确定从哪里开始转换集合。我应该在默认方法内创建一个字典的设置值,然后返回编码?理想情况下,我希望使默认方法能够处理原始编码器阻塞的所有数据类型(我使用Mongo作为数据源,因此日期似乎也会引发这个错误)
任何正确方向的提示都将不胜感激。
编辑:
谢谢你的回答!也许我应该说得更准确些。
我利用这里的答案来解决被翻译的集合的限制,但内部键也是一个问题。
集合中的对象是可转换为__dict__的复杂对象,但它们本身也可以包含其属性的值,这些值可能不适用于json编码器中的基本类型。
这个集合中有很多不同的类型,散列基本上为实体计算一个唯一的id,但在NoSQL的真正精神中,并没有确切地告诉子对象包含什么。
一个对象可能包含开始日期值,而另一个对象可能具有一些其他模式,其中不包含包含“非原始”对象的键。
That is why the only solution I could think of was to extend the JSONEncoder to replace the default method to turn on different cases - but I'm not sure how to go about this and the documentation is ambiguous. In nested objects, does the value returned from default go by key, or is it just a generic include/discard that looks at the whole object? How does that method accommodate nested values? I've looked through previous questions and can't seem to find the best approach to case-specific encoding (which unfortunately seems like what I'm going to need to do here).