將本文件夾內的所有json文件轉換爲xml文件

將本文件夾內的所有json文件轉換爲xml文件

小工具:用於將本文件夾下的所有json文件轉換爲xml文件。
環境:linux環境(若環境爲windows會報“decode”錯誤,在打開文件時選擇windows環境下的編碼格式:GBK)
參考:python:json轉xml

上代碼

import os
from json import loads
from dicttoxml import dicttoxml
from xml.dom.minidom import parseString


def jsonToXml(json_path, xml_path):
    #@abstract: transfer json file to xml file
    #json_path: complete path of the json file
    #xml_path: complete path of the xml file
    with open(json_path,'r',encoding='UTF-8')as json_file:
        load_dict=loads(json_file.read())
    #print(load_dict)
    my_item_func = lambda x: 'Annotation'
    xml = dicttoxml(load_dict,custom_root='Annotations',item_func=my_item_func,attr_type=False)
    dom = parseString(xml)
    #print(dom.toprettyxml())
    #print(type(dom.toprettyxml()))
    with open(xml_path,'w',encoding='UTF-8')as xml_file:
        xml_file.write(dom.toprettyxml())
        
def json_to_xml(json_dir, xml_dir):
    #transfer all json file which in the json_dir to xml_dir
    if(os.path.exists(xml_dir)==False):
        os.makedirs(xml_dir)
    dir = os.listdir(json_dir)
    for file in dir:
        file_list=file.split(".")
        if(file_list[-1] == 'json'):
            jsonToXml(os.path.join(json_dir,file),os.path.join(xml_dir,file_list[0]+'.xml'))  

if __name__ == '__main__':
    #transfer json files in current directory
    j_dir = os.getcwd()
    x_dir = os.getcwd()
    json_to_xml(j_dir, x_dir)
  1. os.getcwd() 用於獲取當前路徑;
  2. file_list[-1] 用於獲取文件的後綴;
  3. dom.toprettyxml()用於將str修改爲更美觀的格式
  4. dicttoxml用於將字典轉換爲xml
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章