用python flask框架在linux开发数据接口的时候,从mysql数据库执行sql获取的数据,通过json.dumps()方法转化会报错,经常会碰到以下两种提示:
TypeError: Object of type 'decimal' is not json serializable jsonify!
TypeError: Object of type 'datetime' is not JSON serializable
这是因为你的数据中包含了datetime和Decimal类型的数据,这两种类型是不能直接进行不能直接进行JSON序列化的!!
查看源码我们可以看到json.dumps()方法中有一个cls的参数,默认为None,
此时,我们再进入SONEncoder这个类,发现这就是Python数据序列化为JSON格式的数据时数据类型的对应关系:
其中并不包含datetime和Decimal两种类型,这个时候如果我们想处理这种数据,就要重新改写这个类,需要先把这两种类型的数据转化为str,然后再进行格式话操作。:
# 记得导入所需的模块
import datetime
import decimal
# 继承原有的JSONEncoder类
class DecEncoder(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, datetime.date):
return obj.strftime("%Y-%m-%d")
super(DecEncoder, self).default(o)
然后,后面使用json.dumps()方法的时候,我们可以加上cls参数:
from datetime import datetime
aa = datetime.now()
dd = json.dumps(aa,cls=DecEncoder)
好了,这样 就不会报错了!收工~~~