Python json 錯誤xx is not JSON serializable解決辦法
更新時間:2017年03月15日 11:16:11 作者:orangleliu
這篇文章主要介紹了Python json 錯誤xx is not JSON serializable解決辦法的相關資料,需要的朋友可以參考下
Python json 錯誤xx is not JSON serializable解決辦法
在使用json的時候經常會遇到xxx is not JSON serializable,也就是無法序列化某些對象。經常使用django的同學知道django里面有個自帶的Encoder來序列化時間等常用的對象。其實我們可以自己定定義對特定類型的對象的序列化,下面看下怎么定義和使用的。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#json_extention
#2014-03-16
#copyright: orangleliu
#license: BSD
'''''
python中dumps方法很好用,可以直接把我們的dict直接序列化為json對象
但是有的時候我們加了一些自定義的類就沒法序列化了,這個時候需要
自定義一些序列化方法
參考:
http://docs.python.org/2.7/library/json.html
例如:
In [3]: from datetime import datetime
In [4]: json_1 = {'num':1112, 'date':datetime.now()}
In [5]: import json
In [6]: json.dumps(json_1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
D:\devsofts\python2.7\lib\site-packages\django\core\management\commands\shell.py
c in <module>()
----> 1 json.dumps(json_1)
TypeError: datetime.datetime(2014, 3, 16, 13, 47, 37, 353000) is not JSON serial
izable
'''
from datetime import datetime
import json
class DateEncoder(json.JSONEncoder ):
def default(self, obj):
if isinstance(obj, datetime):
return obj.__str__()
return json.JSONEncoder.default(self, obj)
json_1 = {'num':1112, 'date':datetime.now()}
print json.dumps(json_1, cls=DateEncoder)
'''''
輸出結果:
PS D:\code\python\python_abc> python .\json_extention.py
{"date": "2014-03-16 13:56:39.003000", "num": 1112}
'''
#我們自定義一個類試試
class User(object):
def __init__(self, name):
self.name = name
class UserEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, User):
return obj.name
return json.JSONEncoder.default(self, obj)
json_2 = {'user':User('orangle')}
print json.dumps(json_2, cls=UserEncoder)
'''''
PS D:\code\python\python_abc> python .\json_extention.py
{"date": "2014-03-16 14:01:46.738000", "num": 1112}
{"user": "orangle"}
'''
定義處理方法是繼承json.JSONEncoder的一個子類,使用的時候是在dumps方法的cls函數(shù)中添加自定義的處理方法。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
Python OpenCV實現(xiàn)傳統(tǒng)圖片格式與base64轉換
Base64是網絡上最常見的用于傳輸8Bit字節(jié)碼的編碼方式之一,本文主要介紹了Python OpenCV實現(xiàn)傳統(tǒng)圖片格式與base64轉換,感興趣的可以參考一下2021-06-06
python+django+rest框架配置創(chuàng)建方法
今天小編就為大家分享一篇python+django+rest框架配置創(chuàng)建方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python使用pymongo模塊操作MongoDB的方法示例
這篇文章主要介紹了Python使用pymongo模塊操作MongoDB的方法,結合實例形式分析了Python基于pymongo模塊連接MongoDB數(shù)據(jù)庫以及增刪改查與日志記錄相關操作技巧,需要的朋友可以參考下2018-07-07

