1、现象
假设你的字典是样子的,你的value是一个datetime类型的值,这时候使用json.dump会报错 TypeError: Object of type 'datetime' is not JSON serializable
# encoding=utf-8
import datetime
import json
if __name__ == '__main__':
data = {"id": 13500499, "update_time": datetime.datetime(2021, 12, 21, 6, 0, 15)}
with open("测试.json", "w") as f:
json.dump(data, f)
2、解决
①写个子类,继承json.JSONEncoder
②重写一下default函数
③json.dump时指定cls为子类
# encoding=utf-8
import datetime
import json
from datetime import date, datetime
class LoadDatetime(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, obj)
if __name__ == '__main__':
data = {"id": 13500499, "update_time": datetime(2021, 12, 21, 6, 0, 15)}
with open("测试.json", "w") as f:
json.dump(data, f, cls=LoadDatetime)
参考 https://blog.csdn.net/IT_xiao_bai/article/details/86686014