解决报错TypeError: Object of type int32 is not JSON serializable

报错原因:

当我们尝试将 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 类默认支持以下对象和类型。

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int and float derived Enumsnumber
Truetrue
Falsefalse
Nonenull

请注意,默认情况下,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。

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python中,当你尝试将某些数据类型转换为JSON格式时,可能会遇到`TypeError: Object of type int64 is not JSON serializable`的错误。这个错误通常是由于尝试将不可序列化的数据类型转换为JSON格式导致的。 根据引用和引用的参考链接,这个错误通常发生在使用`json.dumps()`函数时。它试图将Python对象转换为JSON字符串,但遇到了不能被序列化的数据类型。在你的情况中,错误消息中提到的`int64`数据类型实际上是`numpy.int64`,而不是Python内置的整数类型int。 为了解决这个问题,你可以尝试进行以下操作: 1. 确保你引入了正确的模块和库,特别是`numpy`库。你可以使用`import numpy as np`来引入它。 2. 在转换之前,检查你的数据类型。如果你使用了`numpy`数组或`pandas`数据框,你可能需要将其转换为Python内置的数据类型。你可以使用`.tolist()`方法将`numpy`数组转换为Python列表,并使用`.astype(int)`方法将数据框中的数据类型转换为整数类型。 3. 如果你的数据中包含其他不可序列化的数据类型,例如`float32`或`float64`,你可以使用类似的方法来解决问题。将它们转换为合适的数据类型,例如使用`.astype(float)`将数据类型转换为浮点数。 综上所述,你可以根据上述方法来解决你遇到的问题。记得根据你具体的代码和数据类型的情况进行适当的调整。希望这些解决方法对你有帮助。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [解决Python TypeError: Object of type int64 is not JSON serializable](https://blog.csdn.net/weixin_39561473/article/details/123227500)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [TypeError: Object of type int64 is not JSON serializable](https://blog.csdn.net/weixin_46713695/article/details/125014034)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值