一、json默认的数据类型

二、dumps源码

三、自定义json数据类型

import json
from datetime import datetime, date
print(datetime.today()) # 2019-08-06 19:00:30.485567
print(date.today()) # 2019-08-06
"""
TypeError: Object of type 'datetime' is not JSON serializable
"""
class MyJson(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.strftime('%Y-%m-%d %X')
elif isinstance(o, date):
return o.strftime('%Y-%m-%d')
else:
return super().default(self, o)
res = {'c1': datetime.today(), 'c2': date.today()}
print(json.dumps(res, cls=MyJson)) # {"c1": "2019-08-06 19:00:30", "c2": "2019-08-06"}