Python 之 Json 序列化报错 XXX is not JSON serializable

前记

Python 中使用 json.dumps 时出现 xxx is not JSON serializable

问题一

1
TypeError: Object of type Decimal is not JSON serializable

问题二

1
TypeError: Object of type datetime is not JSON serializable

解决

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import datetime
import decimal

class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return float(obj)
if isinstance(obj, datetime.datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
if isinstance(obj, date):
return obj.strftime("%Y-%m-%d")
return json.JSONEncoder.default(self, obj)

json.dumps(data, cls=JSONEncoder)

JSONEncoder 中的类型可以扩展,加上自己需要的类型即可