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的時候經(jīng)常會遇到xxx is not JSON serializable,也就是無法序列化某些對象。經(jīng)常使用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 下 CMake 安裝配置 OPENCV 4.1.1的方法
這篇文章主要介紹了python 下 CMake 安裝配置 OPENCV 4.1.1的方法,文中給大家提到了CMake 安裝配置 OPENCV 4.1.1 解決各種問題,需要的朋友可以參考下2019-09-09解決Keras TensorFlow 混編中 trainable=False設置無效問題
這篇文章主要介紹了解決Keras TensorFlow 混編中 trainable=False設置無效問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06