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

后续补充

猜你喜欢

转载自blog.csdn.net/u013894391/article/details/103006594
今日推荐