项目中需要大量列表中的数字相加,于是使用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)