TypeError: 921 is not JSON serializable

TypeError: 921 is not JSON serializable

错误说明

输入数据:

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
                ]
            }
        }
    ]
}

问题解决。

猜你喜欢

转载自blog.csdn.net/zengNLP/article/details/128675064
今日推荐