最近在调试之前师兄写的一段代码,在运行的时候把dict类型的结果用json.dump储存为json类型报错,TypeError: Object of type ‘int64’ is not JSON serializable
输出了一下result的结果发现是numpy.int,而json.dump不能识别numpy的数据类型,有两种方法可以解决,第一种是循环把result里的每个数都变成int类型
result[i]['articles'] = [int(part) for part in article_list]
第二种方法是自己写一个序列化的方法,载入json.dump就行
# 自定义序列化方式
class Encoder(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()