場景:在使用了mask rcnn跑實驗后標注了大量地json格式文件,現在打算使用yolo和faster rcnn 跑實驗 所以需要將之前地json文件轉為xml
但是找了很久,沒發現有批量處理的代碼,所以自己寫了一個,經測可用。
使用方法:將我代碼拷貝入一個python文件中;修改34和35行對應參數json_path和xml_path,分別代表要轉的json文件主目錄(有json文件的上一級目錄)和xml文件存放目錄
ps:前面加r是表示取消轉義符 下附代碼 ====
1 # -------------------------------------------------------- 2 # Written by JianFeng Liu, based on python 3 # json file transform to xml file automatically 4 # -------------------------------------------------------- 5 import xmltodict 6 import json 7 import os 8 9 # json to xml 10 def jsonToXml(json_str): 11 try: 12 xml_str="" 13 xml_str = xmltodict.unparse(json_str, encoding='utf-8') 14 except: 15 xml_str = xmltodict.unparse({'request': json_str}, encoding='utf-8') 16 finally: 17 return xml_str 18 19 def json_to_xml(json_path,xml_path): 20 if(os.path.exists(xml_path)==False): 21 os.makedirs(xml_path) 22 dir = os.listdir(json_path) 23 for file in dir: 24 file_list=file.split(".") 25 with open(os.path.join(json_path,file), 'r') as load_f: 26 load_dict = json.load(load_f) 27 json_result = jsonToXml(load_dict) 28 f = open(os.path.join(xml_path,file_list[0]+".xml"), 'w', encoding="UTF-8") 29 f.write(json_result) 30 f.close() 31 32 if __name__ == '__main__': 33 34 json_path=r"G:\jianfeng\project\rubblish_det\source\train_pic_json\111" #該目錄為存放json文件的路徑 ps:目錄中只能存放json文件 35 xml_path=r"G:\jianfeng\project\rubblish_det\source\train_pic_json\222" #該目錄為放xml文件的路徑 36 json_to_xml(json_path,xml_path)