前记
在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
 | 
解决
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | import datetimeimport 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中的类型可以扩展,加上自己需要的类型即可