json写入问题:TypeError: Object of type float32 is not JSON serializable

问题:

字典数据写入json文件时,遇到标题错误

分析:

字典格式化写入json不支持np类型float32,类似还有np.int32、np.array等

解决:

转换np类型为python类型

np.float32 -> float

import numpy as np

a = 1.0998777
a = np.float32(a)
print(type(a))

查看到输出类型:

<class 'numpy.float32'>

强制转换

a = float(a)
print(type(a))
<class 'float'>

np.array->list

b = np.array([1.0998777, 1.0998777])
print(type(b))
b = list(b)
print(type(b))
<class 'numpy.ndarray'>
<class 'list'>

猜你喜欢

转载自blog.csdn.net/dou3516/article/details/121691237