[Python] json 报错'xxx is 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)即可