转json报错:TypeError: Object of type int64 is not JSON serializable
错误:TypeError: Object of type 'int64' is not JSON serializable (或者float32)
在使用json格式保存数据时,经常会遇到xxx is not JSON serializable,也就是无法序列化某些对象格式,我所遇见的是我使用了numpy时,使用了np的数据格式,写入data后,json.dumps(data)失败,我们可以自己定定义对特定类型的对象的序列化,下面看下怎么定义和使用关于np数据类型的自定义。
1.首先,继承json.JSONEncoder,自定义序列化方法。
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NpEncoder, self).default(obj)
2.使用dumps方法(我们可以直接把dict直接序列化为json对象)加上 cls=NpEncoder,data就可以正常序列化了
json.dumps(data, cls=NpEncoder)
其实,很简单,自定义一个序列化方法,然后dumps的时候加上cls=NpEncoder
注:pandas中报这个错误也可以使用
- 使用numpy库报错,TypeError: Object of type 'int64' is not JSON serializable.
- datetimeTypeError: datetime.datetime(2015, 1, 29, 8, 17, 41) is not JSON serializable
- 在使用json.dumps时遇到报错TypeError: Object of type 'float32' is not JSON serializable
- Python3 flask 解析post的json数据时报错,TypeError: Object of type 'bytes' is not JSON serializable
- python-TypeError: Object of type 'Decimal' is not JSON serializable 报错
- Python3运行报错TypeError: Object of type bytes is not JSON serializable
- TypeError: datetime.datetime(2016, 9, 25, 21, 12, 19, 135649) is not JSON serializable解决办法(json无法序列化对象的解决办法)
- TypeError: Object of type 'int32' is not JSON serializable
- TypeError: Object of type 'bytes' is not JSON serializable
- TypeError: ObjectId('') is not JSON serializable
- TypeError: Object of type 'float32' is not JSON serializable
- [scrapy] exceptions.TypeError:XXX is not json serializable
- TypeError:Object of type 'datetime' is not JSON serializable 和 json.dumps函数输出中文乱码解决方案
- json.dump throwing “TypeError: {…} is not JSON serializable”
- python2.7web代码用python3.6运行时,浏览器发送请求报错TypeError: Object of type 'bytes' is not JSON serializable的解决办法
- 【已解决】Object of type 'QuerySet' is not JSON serializable
- flask添加权限的时候出现TypeError: ObjectId('') is not JSON
- [py2neo]TypeError: Neo4j does not support JSON parameters of type int64
- 经典错误之:TypeError: res.json is not a function
- Flask 中使用 JSON 响应页面的 Ajax 请求报错 TypeError: 'dict' object is not callable