设为首页 加入收藏

TOP

[Python] json 报错'xxx is not JSON serializable'的处理方法
2017-09-30 17:01:09 】 浏览:3528
Tags:Python json 报错 ' xxx not JSON serializable' 处理 方法

 

 

1 predictions = self.model.predict(x_data, verbose=0)[0] 
2 y_pred_idx = np.argmax(predictions)
3 y_pred_prob = predictions[y_pred_idx]
4 y_pred_label = self.le.inverse_transform(y_pred_idx) 
5 res = OrderedDict()
6 res['first'] = self.first_label2name[y_pred_label[0]]
7 res['second'] = self.second_label2name[y_pred_label]
8 res['probability'] = y_pred_prob
9 out.write(json.dumps(res, ensure_ascii=False) + '\n')

报错:'0.80454153 is not JSON serializable'

 

输出y_pred_prob的类别:<type 'numpy.float32'>

参考https://stackoverflow.com/questions/27050108/convert-numpy-type-to-python/27050186#27050186中类似问题的解决方案,有个回答中提到:

Ultimately, it looks like json is telling you that an int isn't serializable, but really, it's telling you that this particular np.int32 (or whatever type you actually have) isn't serializable. (No real surprise there -- No np.int32 is serializable). 

 

可以知道,json不能对np.int32或者np.float32等类型进行序列化,可以通过自定义serializer或者直接类型转换来解决。

因此,在第8行显式地把数据转为float类型:res['probability'] = float(y_pred_prob)即可

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇selenium+python开发环境的搭建 下一篇Python之路Day1-Python基础1

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目