python:json轉xml

python讀寫json

json

  1. JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。它基於ECMAScript的一個子集。JSON採用完全獨立於語言的文本格式,但是也使用了類似於C語言家族的習慣(包括C、C++、Java、JavaScript、Perl、Python等)。這些特性使JSON成爲理想的數據交換語言。易於人閱讀和編寫,同時也易於機器解析和生成(一般用於提升網絡傳輸速率)。
  2. JSON在python中分別由list和dict組成。
  3. json模塊提供了四個功能:dumps,dump,loads,load
  • dumps: 將python中的字典轉換爲字符串
  • loads: 將字符串轉換爲字典
  • dump: 將數據寫入json文件中
  • load: 把文件打開,並把字符串變換爲數據類型

參考:python讀寫json文件.

python讀寫xml

#方式一
file = open("路徑",'r',encoding = 'utf-8')
#方式二
with open("路徑",'r',encoding = 'utf-8')as file_obj:
	語句塊

推薦第二種。因爲該種方式可以在任何情況下關閉文件,且條理清晰。

python:json轉xml

  1. 直接自己擼個for循環轉換
  2. 使用庫函數轉換:dicttoxml
  • 安裝庫dicttoxml,該庫是將python中的字典轉換爲xml格式,結合json.loads()函數能給將json內容轉換爲xml格式的內容。

pip install dicttoxml

  • dicttoxml方法中使用custom_root自定義根節點名稱;item_func自定義項目節點名稱;attr_type=False選擇是否添加類型說明,該文選擇不添加。
  • 上代碼
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__':
    #trandfer singal file
    j_path = "F:/清影科技/work/jsontoxml/json/test.json"
    x_path = "F:/清影科技/work/jsontoxml/json/test.xml"
    jsonToXml(j_path,x_path)

    #transfer multi files
    j_dir = "F:/清影科技/work/jsontoxml/json/"
    x_dir = "F:/清影科技/work/jsontoxml/xml/"
    json_to_xml(j_dir, x_dir)
  • 效果:
    在這裏插入圖片描述
    在這裏插入圖片描述

小工具:將本文件夾內的所有json文件轉換爲xml文件

python:xml轉json

後續補充

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章