解决 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) 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章