TypeError: Object of type 'Animal' is not JSON serializable/ 自定义对象 转json串
import json
class Animal(object):
def __init__(self):
self.name = 'tom'
def __repr__(self):
return f'my name is {self.name}&i like apple'
d1 = {
'county': 'china',
'name': Animal()
}
class MyDefault(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Animal):
return str(obj)
return json.JSONEncoder.default(self, obj)
print(json.dumps(d1, cls=MyDefault))