Search code examples
pythonxmljsonxml-serialization

How can i convert an xml file into JSON using python?


I have an XML file which I want to convert into JSON file using python, but its nt working out 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>

The above XML file I am parsing using ElementTree and giving it to Simplejson to serialize like this:

from xml.etree import ElementTree as ET
import simplejson

tree = ET.parse(Xml_file_path)
simplejson.dumps(tree)

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


Solution

  • 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)