您的位置:首页 > 移动开发 > Objective-C

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

2018-01-02 17:43 696 查看
1down
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。
1234567891011121314
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
是支持的。#
python #
json_dumps
1down
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐