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
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)