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