使用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)
相关文章推荐
- 在使用json.dumps时遇到报错TypeError: Object of type 'float32' is not JSON serializable
- TypeError: Object of type 'bytes' is not JSON serializable
- Python3 flask 解析post的json数据时报错,TypeError: Object of type 'bytes' is not JSON serializable
- TypeError: Object of type 'float32' is not JSON serializable
- python2.7web代码用python3.6运行时,浏览器发送请求报错TypeError: Object of type 'bytes' is not JSON serializable的解决办法
- Flask 中使用 JSON 响应页面的 Ajax 请求报错 TypeError: 'dict' object is not callable
- 【已解决】Object of type 'QuerySet' is not JSON serializable
- Python json中的Object of type "xxx" is not JSON serializable通用解决办法
- Scrapy使用shell命令报错scrape shell TypeError: 'float' object is not iterable
- 【已解决】Object of type 'range' is not JSON serializable
- 关于ExtJs使用时报错:TypeError: b[e] is not a constructor
- vue项目使用手机浏览器访问时报错:Uncaught TypeError: Object.assign is not a function
- TypeError: object of type 'zip' has no len()、'zip' object is not subscriptable
- TypeError: url.indexOf is not a function ,使用jquery load()出现错误
- datetimeTypeError: datetime.datetime(2015, 1, 29, 8, 17, 41) is not JSON serializable
- 关于 "Uncaught TypeError: Property 'submit' of object #<HTMLFormElement> is not a function" 的解决方案
- R语言summary()报错object of type 'closure' is not subsettable的原因
- python3中,socket使用send函数时出现的错误:TypeError: a bytes-like object is required, not 'str'
- django object is not JSON serializable error问题解决
- [scrapy] exceptions.TypeError:XXX is not json serializable