栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

记录:TypeError: Object of type int32 is not JSON serializable。

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

记录:TypeError: Object of type int32 is not JSON serializable。

    rect_list = list()

    ...
    rect_list.append(rect1)
    rect_list.append(rect2)
    ...

    rsp = {'rect-list': rect_list}
    return json.dumps(rsp) 

报错

  File "C:UsersmoAppDataLocalProgramsPythonPython39libjsonencoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:UsersmoAppDataLocalProgramsPythonPython39libjsonencoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type int32 is not JSON serializable

原因

字典格式化为JSON不支持numpy.int32。np.float32、np.array等存在类似问题。

解决(两种 方法原理相同)

  • 转Json前,将np类型强制转换为python类型
def cv_rect_to_dict(cv_rect):
    x, y, w, h = cv_rect
    return {'x': int(x), 'y': int(y), 'w': int(w), 'h': int(h)}
  • 继承实现自定义Json Encoder
class ZJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, numpy.integer):
            return int(obj)
        elif isinstance(obj, numpy.floating):
            return float(obj)
        elif isinstance(obj, numpy.ndarray):
            return obj.tolist()
        else:
            return super(ZJsonEncoder, self).default(obj)


用法:
    rsp = {'rect-list': rect_list}
    return json.dumps(rsp, cls=ZJsonEncoder)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/942441.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号