How to convert xml file to JSON using python?

I have an XML file that I want to convert to a JSON file using python, but its nt works for me.

<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> 

In the XML file above, I parse with ElementTree and provide it with Simplejson for serialization as follows:

 from xml.etree import ElementTree as ET import simplejson tree = ET.parse(Xml_file_path) simplejson.dumps(tree) 

This gives me an error: TypeError: xml.etree.ElementTree.ElementTree object at 0x00C49DD0 is not serializable JSON.

+6
source share
4 answers

This is probably what you are looking for:

https://github.com/mutaku/xml2json

 import xml2json s = '''<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>''' print xml2json.xml2json(s) 
+7
source

Another option is xmltodict (full disclosure: I wrote it). It can help you convert your XML to a dict + list + string structure by following this "standard" . This is Expat , so it is very fast and does not require loading the entire XML tree into memory.

Once you have such a data structure, you can serialize it to JSON:

 import xmltodict, json o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>') json.dumps(o) # '{"e": {"a": ["text", "text"]}}' 
+16
source

You can try using xmljson . The code for him is

 from xmljson import badgerfish as bf from xml.etree.ElementTree import fromstring s = '''<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>''' json.dumps(bf.data(fromstring(s))) 
+2
source

Probably the question is how to convert the XML instance data corresponding to the YANG models (IETF RFC7950) into json instance data corresponding to the same YANG and RFC 7951 data models.

I would also like to see a tool for this,

0
source

Source: https://habr.com/ru/post/891273/


All Articles