批量修改json文件的标签值python代码

import os
import json
from tkinter.tix import ButtonBox

def xiugai(old_name,new_name):
    j=0
    for json_file in json_files:
        json_file_ext = os.path.splitext(json_file)

        if json_file_ext[1] == '.json':
            jsonfile = json_dir +'\\'+ json_file

            with open(jsonfile,'r',encoding = 'utf-8') as jf:
                info = json.load(jf)
                
                for i,label in enumerate(info['shapes']):
                    if info['shapes'][i]['label'] == old_name:
                        info['shapes'][i]['label'] = new_name
                        j=j+1
                        # 找到位置进行修改
                # 使用新字典替换修改后的字典
                json_dict = info
            
            # 将替换后的内容写入原文件 
            with open(jsonfile,'w') as new_jf:
                json.dump(json_dict,new_jf)
        
    print('change name over!')
    print(j)
#写入自己放了照片和json文件的文件夹路
#写自己的旧标签名和新标签名
data={"person":"2",
    "cupboard":"6",
    "chair":"1",
    "box":"5",
    "workpiece":"14"
     }
json_dir = './output3'
json_files = os.listdir(json_dir)
for i,key in data.items():
    xiugai(i,key)

如上,我书写了一个字典,通过遍历字典值(标签值)和关键字,传入xiugai函数中,实现批量修改,并计算修改数

你可能感兴趣的:(json,python,开发语言)