報錯:TypeError: Object of type 'datetime' is not JSON serializable
解決方式:
class CJsonEncoder(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)
使用時候只要在json.dumps增加一個cls參數即可:
json.dumps(datalist, cls=CJsonEncoder)
轉載鏈接:https://my.oschina.net/whp/blog/111173