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



1 down vote

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是支持的。


1 down vote

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.

你可能感兴趣的:(python学习笔记)