如果用 json.dumps 一个自定义的类,json自带的编码器是无法解析的
import json
class A:
def __init__(self, a):
self.a = a
def __repr__(self):
return str(self.a)
foo = {'a': 666, 'b': A(666)}
json.dumps(foo)
报错如下
--------------------------------------------------------------------------- TypeError Traceback (most recent call last)in () 7 8 foo = {'a': 666, 'b': A(666)} ----> 9 json.dumps(foo) D:ProgramFilesNoSpaceMiniconda3envspy36libjson__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw) 229 cls is None and indent is None and separators is None and 230 default is None and not sort_keys and not kw): --> 231 return _default_encoder.encode(obj) 232 if cls is None: 233 cls = JSonEncoder D:ProgramFilesNoSpaceMiniconda3envspy36libjsonencoder.py in encode(self, o) 197 # exceptions aren't as detailed. The list call should be roughly 198 # equivalent to the PySequence_Fast that ''.join() would do. --> 199 chunks = self.iterencode(o, _one_shot=True) 200 if not isinstance(chunks, (list, tuple)): 201 chunks = list(chunks) D:ProgramFilesNoSpaceMiniconda3envspy36libjsonencoder.py in iterencode(self, o, _one_shot) 255 self.key_separator, self.item_separator, self.sort_keys, 256 self.skipkeys, _one_shot) --> 257 return _iterencode(o, 0) 258 259 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, D:ProgramFilesNoSpaceMiniconda3envspy36libjsonencoder.py in default(self, o) 178 """ 179 raise TypeError("Object of type '%s' is not JSON serializable" % --> 180 o.__class__.__name__) 181 182 def encode(self, o): TypeError: Object of type 'A' is not JSON serializable
这时就需要继承 json.JSONEncoder,重载 default 方法
class MyJsonEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, A):
return str(o)
return super().default(self, o)
json.dumps(foo, cls=MyJsonEncoder)
输出:
'{"a": 666, "b": "666"}'



