报错原因:
当我们尝试将 numpy int32 对象转换为 JSON 字符串时,会出现 Python“TypeError: Object of type int32 is not JSON serializable”。 要解决该错误,请先将 numpy int 转换为 Python 整数,然后再将其转换为 JSON,例如
int(my_numpy_int)
解决方案:
下面是错误如何发生的示例。
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() 方法,但该方法默认不处理 numpy integers。
要解决该错误,请在序列化之前使用内置的 int()或 float()函数将 numpy int32 对象转换为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'>
默认的 JSON 编码器处理 int 和 float 值,因此我们可以在序列化为 JSON 时使用原生 Python int 而不是 numpy int32。
json.dumps 方法将 Python 对象转换为 JSON 格式的字符串。
或者,您可以从 JSONEncoder 类扩展并在默认方法中处理转换。
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 类扩展而来。
JSONEncoder 类默认支持以下对象和类型。
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int and float derived Enums | number |
True | true |
False | false |
None | null |
请注意,默认情况下,JSONEncoder 类不支持 numpy int32 到 JSON 的转换。
我们可以通过从类扩展并实现返回可序列化对象的 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 的实例,我们将对象转换为 Python int 并返回结果。
如果传入的对象是 np.floating 的实例,我们将其转换为 Python float 并返回结果。
如果对象是 np.ndarray 的实例,我们将其转换为 Python list并返回结果。
在所有其他情况下,我们让基类的默认方法进行序列化。
要使用自定义 JSONEncoder,请在调用 json.dumps() 方法时使用 cls 关键字参数指定它。
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,则使用默认的 JSONEncoder。文章来源:https://www.toymoban.com/news/detail-457188.html
文章来源地址https://www.toymoban.com/news/detail-457188.html
到了这里,关于解决报错TypeError: Object of type int32 is not JSON serializable的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!