如何处理错误“int32类型的对象不是JSON可序列化的”

2024-10-01 17:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图以.json文件格式保存一个dict数据。 当我尝试的时候json.dump文件(JSON,JSON_文件),它抛出错误:int32类型的对象不是JSON可序列化的。在

我知道我用的是数据。在

这是我试过的密码。在

import json
for i in range(1):
    g = Balea_coordinate[i] # numpy array
    h = DM_coordinate[i]  # numpy array
    JSON = {"img_metadata" :  {
            "date" : "date",
            "Method" : "SIFT+RANSACK",
            "filename" : "Balea_",
            "size" : "SIZE",
            "regions":[{"0":{"shape_attributes":{"name":"polygon","all_points_x":[g[0,0,0],g[1,0,0],g[2,0,0],g[3,0,0]],
            "all_points_y":[g[0,0,1],g[1,0,1],g[2,0,1],g[3,0,1]]},
            "region_attributes":{"name":"Logo","type":"Balea"}},
            "1":{"shape_attributes":{"name":"polygon","all_points_x":[h[0,0,0],h[1,0,0],h[2,0,0],h[3,0,0]],
            "all_points_y":[h[0,0,1],h[1,0,1],h[2,0,1],h[3,0,1]]},
            "region_attributes":{"name":"Logo","type":"DM"}}}]}}
    with open('personal.json', 'w') as json_file:
        json.dump(JSON, json_file)
´´´

Tags: 文件数据namenumpyjsoncoordinatedatedm
1条回答
网友
1楼 · 发布于 2024-10-01 17:34:53

我建议扩展默认的JSONEncoder来处理数字.int32类型(或任何其他所需类型)。在

class npEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.int32):
            return int(obj)
        return json.JSONEncoder.default(self, obj)

然后在json.dump(JSON, json_file, cls=npEncoder)中使用它。根据您的需求,简单的转换np.int32 -> int可能不够。在

相关问题 更多 >

    热门问题