這篇文章主要介紹python如何使用json序列化datetime類型實(shí)例解析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
使用python的json模塊序列化時(shí)間或者其他不支持的類型時(shí)會(huì)拋異常,例如下面的代碼:
# -*- coding: cp936 -*- from datetime import datetime import json if __name__=='__main__': now = datetime.now() json.dumps({'now':now})
運(yùn)行會(huì)出現(xiàn)下面的錯(cuò)誤信息:
Traceback (most recent call last): File "C:\Users\xx\Desktop\t.py", line 8, in <module> json.dumps({'now':now}) File "C:\Python27\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "C:\Python27\lib\json\encoder.py", line 201, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Python27\lib\json\encoder.py", line 264, in iterencode return _iterencode(o, 0) File "C:\Python27\lib\json\encoder.py", line 178, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: datetime.datetime(2012, 12, 26, 11, 51, 33, 409000) is not JSON serializable
意思是說(shuō)datetime類不支持Json序列化
我們需要對(duì)json做下擴(kuò)展,讓它可以支持datetime類型。
class ComplexEncoder(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)
在調(diào)用json.dumps時(shí)需要指定cls參數(shù)為ComplexEncoder
例如:
json.dumps({'now':now}, cls=ComplexEncoder)
以上是“python如何使用json序列化datetime類型實(shí)例解析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
文章題目:python如何使用json序列化datetime類型實(shí)例解析-創(chuàng)新互聯(lián)
文章出自:http://www.rwnh.cn/article36/cejisg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、網(wǎng)站改版、建站公司、外貿(mào)網(wǎng)站建設(shè)、小程序開(kāi)發(fā)、云服務(wù)器
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容