python解决json.dump(字典)时报错Object of type ‘float32‘ is not JSON serializable
Posted Better Bench
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python解决json.dump(字典)时报错Object of type ‘float32‘ is not JSON serializable相关的知识,希望对你有一定的参考价值。
1 问题
json.dump原生不支持字典类型,会报错Object of type ‘float32’ is not JSON serializable
import json
dict = {'我':1,'是':2,'帅':3,'哥':4}
json.dump(dict, open('history.json', 'w'))
2 解决办法
自定义一个类
import numpy as np
class NumpyEncoder(json.JSONEncoder):
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
dict = {'我':1,'是':2,'帅':3,'哥':4}
json.dump(dict, open('history.json', 'w'),cls=NumpyEncoder)
以上是关于python解决json.dump(字典)时报错Object of type ‘float32‘ is not JSON serializable的主要内容,如果未能解决你的问题,请参考以下文章
Python中json文件处理的四个函数json.dumps()json.loads()json.dump()和json.load()的区分
python3 django2.0 在生成数据库表时报错: TypeError: __init__() missing 1 required positional argument: 'o(代
什么是序列化,Python中json的load,loads,dump,dumps和pickle的load,loads,dump,dumps的区别