问题描述:
利用http协议进行数据传输时,经常会用到json格式。当待编码数据类型为字符串时,json编码不会遇到问题。对于自定义的数据,就会遇到编码错误问题。
TypeError: Object of type float32 is not JSON serializable
之前经常使用的数据类型编码居然报错了,奇怪的是在python交互环境中运行没问题。
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=7, micro=7, releaselevel='final', serial=0)
>>> import json
>>> rst = "{'result': {'rois': {'car': [[236.0, 254.0, 626.0, 381.0, 0.94369984]]}, 'time': 0.08653140068054199, 'pvid': '0600f0c7-2188-4ab4-a601-08ec5e43cb8d'}, 'message': 'OK', 'returncode': 0}"
>>> json.dumps(rst)
'"{\'result\': {\'rois\': {\'car\': [[236.0, 254.0, 626.0, 381.0, 0.94369984]]}, \'time\': 0.08653140068054199, \'pvid\': \'0600f0c7-2188-4ab4-a601-08ec5e43cb8d\'}, \'message\': \'OK\', \'returncode\': 0}"'
>>> json.dumps(eval(rst))
'{"result": {"rois": {"car": [[236.0, 254.0, 626.0, 381.0, 0.94369984]]}, "time": 0.08653140068054199, "pvid": "0600f0c7-2188-4ab4-a601-08ec5e43cb8d"}, "message": "OK", "returncode": 0}'
>>> type(rst)
<class 'str'>
>>> type(eval(rst))
<class 'dict'>
解决过程:
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
- 通过安装现有模块,来解决该问题
pip install numpyencoder #安装编码模块
#代码中使用方式
from numpyencoder import NumpyEncoder
json.dumps(result,cls=NumpyEncoder)
参考文献: