解決 json.dump 報錯:TypeError - Object of type xxx is not JSON serializable

在python中導入json包可以方便地操作json文件,但是偶爾會遇到 TypeError: Object of type xxx is not JSON serializable 錯誤,通常報錯的位置是很正常的int或float,本文記錄該問題解決方法。

自定義序列化方法

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()
        if isinstance(obj, time):
            return obj.__str__()
        else:
            return super(NpEncoder, self).default(obj)

調用json包時加入

json.dumps(data, cls=MyEncoder) 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章