json文件解析并修改值

json文件解析并修改值

针对使用 anylabeling 对数据标记,会出现标签错误情况,修改json文件的label(针对单类)。如果不会使用该方法标记,可查看这篇博客

[ ] 表示一个数组,{ } 表示一个对象,在对象中还可以包含对象的属性,属性也可能是另外一个类。" " 代表的是属性值,:代表是前后的关系,冒号前是属性的名称,后面是属性的值,这个值可以是基本数据类型,可以是引用类数据类型。

代码如下:

{
  "version": "0.3.3",
  "flags": {},
  "shapes": [
    {
      "label": "brick",
      "text": "",
      "points": [
        [
          789.0,
          594.0
        ],
        ......
        [
          786.0,
          597.0
        ],
      ]
       "group_id": null,
      "shape_type": "polygon",
      "flags": {}
     }
   ],
  "imagePath": "1701656522935_5660202.png",
  "imageData": null,
  "imageHeight": 1240,
  "imageWidth": 1624,
  "text": ""
}

分析:

第一层是一个大括号{ }中的json数组,json数组中包含version,flags,shapes,imagePath,imageData,imageHeight,imageWidth,text.等属性。
第二层是shape的jsonArray属性,每个大括号代表一个对象,每个对象中有label,text,points,group_id,shape_type,flags等属性。

目标:修改label的值

代码:

import os
import json

def read_json(jsonPath):
    with open(jsonPath,"r") as path_json:
        jsonx=json.load(path_json)
        for shape in jsonx["shapes"]:
            obj_cls = str(shape["label"])

            if(obj_cls != "brick"):
                shape["label"] = "brick"
    return jsonx

def write_json(jsonPath,params):
    with open(jsonPath, "w",encoding='utf-8') as path_json:
        json.dump(params,path_json, indent=4, ensure_ascii=False)


if __name__=="__main__":
    json_path = "E:\\Tensor_YOLO\\yolov5_6.0\\yolov5-6.0\\data\\images\\json_file\\modify_label\\"#文件路径
    list_json = os.listdir(json_path)
    for cnt, json_name in enumerate(list_json):
        file,fileext = os.path.splitext(json_name)
        if(fileext == ".json"):
            path_json = json_path + json_name
            data = read_json(path_json)
            write_json(path_json,data)
        else:
            pass
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值