json寫入問題:TypeError: Object of type float32 is not JSON serializable

問題描述

在將一個字典數據寫入json文件時,遇到標題錯誤

問題分析

打印錯誤數據的數據類型type(),發現數據的類型為numpy.float32,python的內置類型float可以寫入json,然而numpy類型的float不能寫入json,所以應將numpy.float32轉換成python內置的數據類型float

  • 附:numpy.array同樣不能寫入json文件,需要將numpy.array轉換成list,例如a.tolist()

問題解決

使用a.item()或np.asscalar(a)將NumPy值轉換為本機Python類型

import numpy as np
# examples using a.item()
type(np.float32(0).item()) # <type 'float'>
type(np.float64(0).item()) # <type 'float'>
type(np.uint32(0).item())  # <type 'long'>
# examples using np.asscalar(a)
type(np.asscalar(np.int16(0)))   # <type 'int'>
type(np.asscalar(np.cfloat(0)))  # <type 'complex'>
type(np.asscalar(np.datetime64(0)))  # <type 'datetime.datetime'>
type(np.asscalar(np.timedelta64(0))) # <type 'datetime.timedelta'>

問題二

上面問題涉及的是一個numpy值,將其轉換成python內置類型即可,然而又遇到一個新問題,一個list,里面的每個元素都是numpy.int32類型,將其寫入json報錯:TypeError: Object of type int32 is not JSON serializable

問題分析

受問題一的啟發,我將list中的每個元素都用item函數轉換成python的內置類型,然而依舊報錯:TypeError: Object of type int32 is not JSON serializable

問題解決

先將list轉換成numpy.array,在將numpy.array轉換成list

import numpy as np
import json
b=np.array(a).tolist()
json_str=json.dumps(b)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。