错误说明
输入数据:
rt = {'result': [{'bp4': {'text': '', 'coord': [1746, 614, 1828, 614, 1828, 658, 1745, 658]}, 'bp2': {'text': '', 'coord': [921, 612, 1003, 613, 1003, 656, 921, 656]}}]}
报错代码:
s = json.dumps(rt, indent=4)
json转为字符串时,报错如下:
TypeError: 921 is not JSON serializable
错误原因
原因分析:921 的数据类型应该是json无法支持的。
打印数据的type信息如下:
打印:
print(type(item['coord'][0]))
输出:
<class 'numpy.int64'>
修改方法
将类型转为int即可
item['coord'][0] = int(item['coord'][0])
再次打印:
{
"result": [
{
"bp4": {
"text": "",
"coord": [
1746,
614,
1828,
614,
1828,
658,
1745,
658
]
},
"bp2": {
"text": "",
"coord": [
921,
612,
1003,
613,
1003,
656,
921,
656
]
}
}
]
}
问题解决。
当尝试将包含numpy.int64类型的对象转换为JSON字符串时,会遇到TypeError:921isnotJSONserializable的错误。原因是JSON不支持numpy的int64类型。解决方法是将这类数据转换为常规的int类型。在示例中,将item[coord][0]转换为int后,问题得到解决。
2175

被折叠的 条评论
为什么被折叠?



