報錯原因:
當(dāng)我們嘗試將 numpy int32 對象轉(zhuǎn)換為 JSON 字符串時,會出現(xiàn) Python“TypeError: Object of type int32 is not JSON serializable”。 要解決該錯誤,請先將 numpy int 轉(zhuǎn)換為 Python 整數(shù),然后再將其轉(zhuǎn)換為 JSON,例如
int(my_numpy_int)
解決方案:
下面是錯誤如何發(fā)生的示例。
import json
import numpy as np
salary = np.power(50, 2, dtype=np.int32)
# ?? TypeError: Object of type int32 is not JSON serializable
json_str = json.dumps({'salary': salary})
我們嘗試將 numpy int32 對象傳遞給 json.dumps() 方法,但該方法默認(rèn)不處理 numpy integers。
要解決該錯誤,請在序列化之前使用內(nèi)置的 int()或 float()函數(shù)將 numpy int32 對象轉(zhuǎn)換為Python integer。
import json
import numpy as np
salary = np.power(50, 2, dtype=np.int32)
# ? convert to Python native int
json_str = json.dumps({'salary': int(salary)})
print(json_str) # ??? '{"salary": 2500}'
print(type(json_str)) # ??? <class 'str'>
默認(rèn)的 JSON 編碼器處理 int 和 float 值,因此我們可以在序列化為 JSON 時使用原生 Python int 而不是 numpy int32。
json.dumps 方法將 Python 對象轉(zhuǎn)換為 JSON 格式的字符串。
或者,您可以從 JSONEncoder 類擴(kuò)展并在默認(rèn)方法中處理轉(zhuǎn)換。
import json
import numpy as np
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
salary = np.power(50, 2, dtype=np.int32)
json_str = json.dumps({'salary': salary}, cls=NpEncoder)
print(json_str) # ??? {"salary": 2500}
print(type(json_str)) # ??? <class 'str'>
我們從 JSONEncoder 類擴(kuò)展而來。
JSONEncoder 類默認(rèn)支持以下對象和類型。
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int and float derived Enums | number |
True | true |
False | false |
None | null |
請注意,默認(rèn)情況下,JSONEncoder 類不支持 numpy int32 到 JSON 的轉(zhuǎn)換。?
我們可以通過從類擴(kuò)展并實(shí)現(xiàn)返回可序列化對象的 default() 方法來處理這個問題。
import json
import numpy as np
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
如果傳入的對象是 np.integer 的實(shí)例,我們將對象轉(zhuǎn)換為 Python int 并返回結(jié)果。
如果傳入的對象是 np.floating 的實(shí)例,我們將其轉(zhuǎn)換為 Python float 并返回結(jié)果。
如果對象是 np.ndarray 的實(shí)例,我們將其轉(zhuǎn)換為 Python list并返回結(jié)果。
在所有其他情況下,我們讓基類的默認(rèn)方法進(jìn)行序列化。
要使用自定義 JSONEncoder,請在調(diào)用 json.dumps() 方法時使用 cls 關(guān)鍵字參數(shù)指定它。
import json
import numpy as np
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
salary = np.power(50, 2, dtype=np.int32)
# ? provide cls keyword argument
json_str = json.dumps({'salary': salary}, cls=NpEncoder)
print(json_str) # ??? {"salary": 2500}
print(type(json_str)) # ??? <class 'str'>
如果您不提供 'cls
'?kwarg,則使用默認(rèn)的 JSONEncoder。文章來源:http://www.zghlxwxcb.cn/news/detail-457188.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-457188.html
到了這里,關(guān)于解決報錯TypeError: Object of type int32 is not JSON serializable的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!