XML to JSON? Is it hard to hear the pain, are the format of structured data necessary for this conversion? Yes, actually I also feel bored, but hands itch, always want to try. Online can also find a conversion tool called xmltodict, also very useful. My method is as follows, the principle is very simple, the code is also very short.
XML file: Testxml.xml
<?xml version= "1.0" encoding= "Utf-8"?><root> <person age= "Up" > <name> Zhang San </name> <sex> men </sex> </person> <person age= "des=" "Hello" > <name> John Doe </name> <sex> Women </sex> </person></root>
Python code:
From Xml.etree import ElementTree as Et;import json# reads the node from the XML file into JSON format and saves it to the file print (' Read node from xmlfile, transfer th EM to JSON, and save into Jsonfile: ') root=et.parse ("Testxml.xml"), F=open (' Testjson.json ', ' a ', encoding= "UTF8"); Each in root.getiterator (' person '): tempdict=each.attrib for Childnode in Each.getchildren (): tempdict[ Childnode.tag]=childnode.text tempjson=json.dumps (tempdict,ensure_ascii=false) print (TempJson) F.write (tempjson+ "\ n"), F.close () #从json文件中读取 and prints print (' Read JSON from Jsonfile: ') for Eachjson in open (' Testjson.json ' , ' R ', encoding= ' UTF8 '): tempstr=json.loads (Eachjson); Print (TEMPSTR)
The results are as follows:
Python does not implement XML-to-JSON with third-party packages