10

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.

1
  • 1
    You have to understand that the element tree object isn't a complete representation of the XML file, it only provides methods to access whatever parts of the XML file you want. The answer for using the xml2json module will meet your needs.
    – ratmatz
    Jun 24, 2011 at 12:37

4 Answers 4

23

Another option is xmltodict (full disclosure: I wrote it). It can help you convert your XML to a dict+list+string structure, following this "standard". It is Expat-based, so it's very fast and doesn't need to load the whole XML tree in memory.

Once you have that 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"]}}'
8

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)
1
  • I am getting an error in Python3. I believe this function works for Python2. Nov 15, 2022 at 3:01
2

You can try to use xmljson. The code for the same 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)))
0

See xml_to_json. It supports xsd schema, e.g. type definitions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.