Since JSON-formatted files are highly convenient to work with and produce a large number of XML-formatted files every day, there is a need to convert XML-formatted files into JSON-formatted files.
Directly below the code, there are two versions, according to the requirements of the free choice:
#!/usr/bin/python# -*- coding: utf-8 -*-#Function:Xml_To_Json#version 1.0#Author: Herman#需要用到的两个模块import xmltodict; import json;#定义函数def pythonXmlToJson(): with open(‘filename.xml‘, ‘r‘) as f: xmlStr = f.read() convertedDict = xmltodict.parse(xmlStr); jsonStr = json.dumps(convertedDict, indent=1); print jsonStr;#执行函数if __name__=="__main__": pythonXmlToJson();
#!/usr/bin/python# -*- coding: utf-8 -*-#Function:Xml_To_Json#version 1.1#Author: Herman#Date: 2018-06-01#Usage: python Xml_To_Json.py xmlfile_dir >> tar_dirimport xmltodict;import json;import sys;def pythonXmlToJson(): with open(sys.argv[1], ‘r‘) as f: xmlStr = f.read() convertedDict = xmltodict.parse(xmlStr); jsonStr = json.dumps(convertedDict, indent=1); print jsonStr;if __name__=="__main__": pythonXmlToJson();
The difference between the two versions is obvious, the first lacks flexibility, the second uses a similar position variable in the shell to make the Python script more flexible.
Ps:python study, we have what better way to achieve, welcome message discussion Oh ~
Python: Converting an XML format file into a JSON-formatted file