在使用json.dumps时遇到报错TypeError: Object of type 'float32' is not JSON serializable

本文介绍如何解决Numpy数组不能直接被JSON序列化的问题,通过自定义编码器实现np.int/np.float/np.array等类型的转换。

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




 

This is not supported by default, but you can make it work quite easily! There are several things you'll want to encode if you want the exact same data back:

  • The data itself, which you can get with obj.tolist() as @travelingbones mentioned. Sometimes this may be good enough.
  • The data type. I feel this is important in quite some cases.
  • The dimension (not necessarily 2D), which could be derived from the above if you assume the input is indeed always a 'rectangular' grid.
  • The memory order (row- or column-major). This doesn't often matter, but sometimes it does (e.g. performance), so why not save everything?

Furthermore, your numpy array could part of your data structure, e.g. you have a list with some matrices inside. For that you could use a custom encoder which basically does the above.

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

a = np.array([1, 2, 3])

print(json.dumps({'aa': [2, (2, 3, 4), a], 'bb': [2]}, cls=NumpyEncoder))

{"aa": [2, [2, 3, 4], [1, 2, 3]], "bb": [2]}


2、

自己写一个encoder去继承jsonencoder 
 

在使用json.dumps时遇到报错TypeError: Object of type 'float32' is not JSON serializable

google后找到方法 Convert numpy type to python

      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
      
class MyEncoder(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(MyEncoder, self).default(obj)
json.dumps(numpy.float32(1.2), cls=MyEncoder)
json.dumps(numpy.arange(12), cls=MyEncoder)
json.dump({'a': numpy.int32(42)},fp,cls=MyEncoder)

我的理解是np.int/np.float/np.array这样的数据格式不支持json serializable,而python自身的int/float/list是支持的。


This is not supported by default, but you can make it work quite easily! There are several things you'll want to encode if you want the exact same data back:

  • The data itself, which you can get with obj.tolist() as @travelingbones mentioned. Sometimes this may be good enough.
  • The data type. I feel this is important in quite some cases.
  • The dimension (not necessarily 2D), which could be derived from the above if you assume the input is indeed always a 'rectangular' grid.
  • The memory order (row- or column-major). This doesn't often matter, but sometimes it does (e.g. performance), so why not save everything?

Furthermore, your numpy array could part of your data structure, e.g. you have a list with some matrices inside. For that you could use a custom encoder which basically does the above.

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值