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

本文介绍如何在将numpy类型的rect_list转换为JSON时遇到TypeError,通过cv_rect_to_dict函数强制类型转换或自定义ZJsonEncoder来解决。重点在于确保np.int32和np.float32等转换为Python类型并适配JSON编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    rect_list = list()

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

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

报错

  File "C:\Users\mo\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\mo\AppData\Local\Programs\Python\Python39\lib\json\encoder.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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值