File /opt/conda/lib/python3.9/json/encoder.py:199, in JSONEncoder.encode(self, o) 195return encode_basestring(o) 196# This doesn't pass the iterator directly to ''.join() because the 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) 200ifnotisinstance(chunks, (list, tuple)): 201 chunks = list(chunks)
File /opt/conda/lib/python3.9/json/encoder.py:179, in JSONEncoder.default(self, o) 160defdefault(self, o): 161"""Implement this method in a subclass such that it returns 162 a serializable object for ``o``, or calls the base implementation 163 (to raise a ``TypeError``). (...) 177 178 """ --> 179raise TypeError(f'Object of type {o.__class__.__name__} ' 180f'is not JSON serializable')
TypeError: Object of type Person isnot JSON serializable
我们仔细观察报错信息, 提示 Person 不是一个 JSON 序列化对象
1
TypeError: Object of type Person isnot JSON serializable
那么问题来了, 我们如何把各种各样的 Python 对象序列化成 JSON 格式?
Google 和查阅官方文档后你会发现 dumps 方法提供了一个 cls 参数, 我们可以自己编写一个序列化类, 告诉该他该如何dumps这个对象.