您好,登錄后才能下訂單哦!
python2.7中 集成了json的處理(simplejson),但在實際應(yīng)用中,從mysql查詢出來的數(shù)據(jù),通常有日期格式,這時候,會報一個錯:
TypeError: datetime.datetime(2007, 7, 23, 12, 24, 25) is not JSON serializable
說明日期轉(zhuǎn)換出問題,后來再網(wǎng)上找到了解決辦法。
import json from datetime import date, datetime def __default(obj): if isinstance(obj, datetime): return obj.strftime('%Y-%m-%dT%H:%M:%S') elif isinstance(obj, date): return obj.strftime('%Y-%m-%d') else: raise TypeError('%r is not JSON serializable' % obj) print json.dumps({ 'd': datetime.now(), 'today': date.today(), 'x': 111 }, default=__default)
采用類似的方式,在得到mysql數(shù)據(jù)集后,需要序列化時,用如下方式就可以了。
conn=self.getConnection(); cursor=conn.cursor(); cursor.execute(sqlText,params); result=cursor.fetchall() jsonstr=json.dumps(myresult,default=__default) print jsonstr
關(guān)鍵點在于覆蓋了default 方法。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。