Python JSON编码器 - 默认方法



我想使我的类JSON序列化,并试图通过JSONEncoder类扩展它。但是,为什么default函数在应该是我的类的方法时将o参数采用。

我想序列化我的类对象,而不是传递给方法的第三个对象?

在子类中实现此方法,以便它返回o的序列化对象,或调用基本实现(提高typeError)。

def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return JSONEncoder.default(self, o)

您应该做这样的事情:

>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return [obj.real, obj.imag]
...         # Let the base class default method raise the TypeError
...         return json.JSONEncoder.default(self, obj)

也许您终于忘记了JSON。
看看JSON DOC

最新更新