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

这篇具有很好参考价值的文章主要介绍了解决报错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 类默认支持以下对象和类型。

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

到了这里,关于解决报错TypeError: Object of type int32 is not JSON serializable的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • Django去访问web api接口Object of type Session is not JSON serializable

    解决方案:settings.py中加入 :SESSION_SERIALIZER = \\\'django.contrib.sessions.serializers.PickleSerializer\\\' 事由:Django去访问一个web api接口,两次连接之间需要通过Session()保持身份验证。 加入SESSION_SERIALIZER = \\\'django.contrib.sessions.serializers.PickleSerializer\\\' 后解决。  

    2024年02月04日
    浏览(5)
  • python常见错误-TypeError: ‘int‘ object is not iterable

    可能大家在Python编程过程中经常会遇到​ ​TypeError: \\\'int\\\' object is not iterable​ ​的错误。这是因为我们尝试迭代一个整数对象,但Python无法迭代整数。 这个错误经常是用for循环迭代整数。例如以下代码: 运行以上代码会得到以下错误信息:TypeError: \\\'int\\\' object is not iterable 要解

    2024年04月14日
    浏览(14)
  • Stable Diffusion图生图报错TypeError: argument of type ‘NoneType‘ is not iterable如何解决?

    Stable Diffusion图生图报错TypeError: argument of type ‘NoneType‘ is not iterable如何解决?

    之前运行都没事,突然莫名开始报错,试了很多方法找不到原因,求大神指路~    

    2024年02月04日
    浏览(13)
  • pip报TypeError: ‘type‘ object is not subscriptable错误

    pip报TypeError: ‘type‘ object is not subscriptable错误

    因为安装 Manim库,中间下载 colour 组件时因为更新pip版本到 23.1.2 ,与python3.9.0 适配的 pip version 19.2.3 版本矛盾,导致后续无法正常使用python,出现如下报错: 修复 pip 的思路很简单,出问题的并不是 python ,而是因为 pip 的版本等级太高,因此想办法能够把 pip 的版本降低就可

    2024年02月15日
    浏览(14)
  • python 报错TypeError: object of type ‘NoneType‘ has no len()处理

    在编程过程中,我们经常会遇到各种异常情况。其中之一就是TypeError异常,它表示操作或函数应用于了错误的数据类型。在本文中,我们将重点讨论TypeError异常中的一种常见情况:当对象为NoneType时,调用len()函数会引发TypeError异常。 在Python中,NoneType是一个特殊的数据类型,

    2024年02月06日
    浏览(10)
  • python 报错TypeError: ‘float‘ object is not callable

    python 报错TypeError: ‘float‘ object is not callable

    python公式中少打了乘号“*”,如下图所示 一般是变量名与函数冲突,如本文中前面代码用到sum,后面直接用sum()函数同样报错,下图: 检查公式是否少打“*”号,python中对格式要求比较严格,不能直接用数学中省略符号的算式 调用函数,sum()函数用np.sum()函数 python报

    2024年02月10日
    浏览(11)
  • 成功解决TypeError: ‘<‘ not supported between instances of ‘str‘ and ‘int‘

    成功解决TypeError: \\\'\\\' not supported between instances of \\\'str\\\' and \\\'int\\\' 目录 解决问题 解决思路 解决方法 TypeError: \\\'\\\' not supported between instances of \\\'str\\\' and \\\'int\\\' 类型错误:\\\'\\\'在\\\'str\\\'和\\\'int\\\'实例之间不支持

    2024年02月14日
    浏览(7)
  • 【Python】成功解决TypeError: object of type ‘numpy.float64‘ has no len()

    【Python】成功解决TypeError: object of type ‘numpy.float64‘ has no len()

    【Python】成功解决TypeError: object of type ‘numpy.float64’ has no len() 🌈 个人主页:高斯小哥 🔥 高质量专栏:Matplotlib之旅:零基础精通数据可视化、Python基础【高质量合集】、PyTorch零基础入门教程👈 希望得到您的订阅和支持~ 💡 创作高质量博文(平均质量分92+),分享更多关于

    2024年04月17日
    浏览(25)
  • 完美解决TypeError: ‘method‘ object is not subscriptable

    完美解决TypeError: ‘method‘ object is not subscriptable 下滑查看解决方法 TypeError: ‘method‘ object is not subscriptable 这个错误通常出现在尝试对一个方法进行索引操作时。 下滑查看解决方法 可能有以下几种原因导致这个错误: 方法名写错:请检查方法名是否正确拼写并确保正确引用

    2024年02月07日
    浏览(8)
  • 【已解决TypeError: ‘dict‘ object is not callable】

    【已解决TypeError: ‘dict‘ object is not callable】

    情况1: 取字典内容的时候使用的是() 解决: 将()改为[ ] 情况2: 原来已经定义过dict函数,此时想使用python内置函数就会报错 可以看到如果我们先定义一个dict,那内置函数就会报错。 解决: 将之前定义的dict函数删掉 删除方法:你可以直接删掉函数重新运行,也可以

    2024年02月15日
    浏览(10)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包