解決TypeError: Object of type xxx is not JSON serializable錯誤問題
TypeError: Object of type xxx is not JSON serializable
問題描述
在導(dǎo)入Python json包,調(diào)用json.dump/dumps函數(shù)時,可能會遇到TypeError: Object of type xxx is not JSON serializable錯誤,也就是無法序列化某些對象格式。
解決辦法
默認(rèn)的編碼函數(shù)很多數(shù)據(jù)類型都不能編碼,自定義序列化,因此可以自己寫一個Myencoder去繼承json.JSONEncoder
具體如下:
class MyEncoder(json.JSONEncoder): ? ? def default(self, obj): ? ? ? ? if isinstance(obj, np.integer): ? ? ? ? ? ? return int(obj) ? ? ? ? elif isinstance(obj, np.floating): ? ? ? ? ? ? return float(obj) ? ? ? ? elif isinstance(obj, np.ndarray): ? ? ? ? ? ? return obj.tolist() ? ? ? ? else: ? ? ? ? ? ? return super(MyEncoder, self).default(obj)
然后在調(diào)用json.dump/dumps時,指定使用自定義序列化方法
json.dumps(data, cls=MyEncoder)?
dict to json
def dict_to_json(dict_obj,name, Mycls = None): ? ? js_obj = json.dumps(dict_obj, cls = Mycls, indent=4) ? ? with open(name, 'w') as file_obj: ? ? ? ? file_obj.write(js_obj)
json to dict
def json_to_dict(filepath, Mycls = None): ? ? with open(filepath,'r') as js_obj: ? ? ? ? dict_obj = json.load(js_obj, cls = Mycls) ? ? return dict_obj
TypeError: Object of type ‘int64’ is not JSON serializable (或者float32)
在使用json格式保存數(shù)據(jù)時,經(jīng)常會遇到xxx is not JSON serializable,也就是無法序列化某些對象格式,我所遇見的是我使用了numpy時,使用了np的數(shù)據(jù)格式,寫入data后,json.dumps(data)失敗,我們可以自己定定義對特定類型的對象的序列化
下面看下怎么定義和使用關(guān)于np數(shù)據(jù)類型的自定義。
1.首先,繼承json.JSONEncoder,自定義序列化方法。
class NpEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): return float(obj) elif isinstance(obj, np.ndarray): return obj.tolist() else: return super(NpEncoder, self).default(obj)
2.使用dumps方法(我們可以直接把dict直接序列化為json對象)加上 cls=NpEncoder,data就可以正常序列化了
json.dumps(data, cls=NpEncoder)
其實(shí),很簡單,自定義一個序列化方法,然后dumps的時候加上cls=NpEncoder
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解如何用TensorFlow訓(xùn)練和識別/分類自定義圖片
這篇文章主要介紹了詳解如何用TensorFlow訓(xùn)練和識別/分類自定義圖片,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Pygame實(shí)戰(zhàn)之實(shí)現(xiàn)扎氣球游戲
這篇文章主要為大家介紹了利用Python中的Pygame模塊實(shí)現(xiàn)的一個扎氣球游戲,文中的示例代碼講解詳細(xì),對我們了解Pygame模塊有一定的幫助,感興趣的可以學(xué)習(xí)一下2021-12-12

