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

使用numpy库报错,TypeError: Object of type 'int64' is not JSON serializable.

2019-03-12 18:19 1976 查看

项目中需要大量列表中的数字相加,于是使用numpy库,但是在json转换时报错。
开始以为是含有numpy类型的字典不能转换为json字符串,后来转换成list依然没有解决。
google后,找到解决办法,重新定义json类。

class NumpyEncoder(json.JSONEncoder):
""" Special json encoder for numpy types """
def default(self, obj):
if isinstance(obj, (numpy.int_, numpy.intc, numpy.intp, numpy.int8,
numpy.int16, numpy.int32, numpy.int64, numpy.uint8,
numpy.uint16, numpy.uint32, numpy.uint64)):
return int(obj)
elif isinstance(obj, (numpy.float_, numpy.float16, numpy.float32,
numpy.float64)):
return float(obj)
elif isinstance(obj, (numpy.ndarray,)):
return obj.tolist()
return json.JSONEncoder.default(self, obj)

使用时:

import json
operation = json.dumps(operation, cls=NumpyEncoder)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐