xmltodict (full disclosure: I wrote 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"]}}'
Answer from Martin Blech on Stack Overflow
🌐
PyPI
pypi.org › project › xmljson
xmljson · PyPI
Converts XML into JSON/Python dicts/arrays and vice-versa.
      » pip install xmljson
    
Published   Apr 25, 2020
Version   0.2.1
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-xml-to-json
Python - XML to JSON - GeeksforGeeks
July 12, 2025 - We use xml_data as input string and generate python object, so we use json.dumps() ... Here, json_data is the variable used to store the generated object. ... # Program to convert an xml # file to json file # import json module and xmltodict ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-xml-to-json-dict
Python XML to JSON, XML to Dict | DigitalOcean
August 3, 2022 - Apart from that, using the open(...) function was straightforward, we used it get a File descriptor and then parsed the file into a JSON object. As the module name suggest itself, xmltodict actually converts the XML data we provide to just a simply Python dictionary.
🌐
PythonForBeginners.com
pythonforbeginners.com › home › convert xml to json in python
Convert XML to JSON in Python - PythonForBeginners.com
February 24, 2023 - The parse() method takes an XML string as its input argument and returns the corresponding dictionary. Next, we will convert the python dictionary to a JSON string. For this, we will use the dumps() method defined in the json module.
🌐
Quora
quora.com › How-can-I-convert-XML-to-JSON-in-Python
How to convert XML to JSON in Python - Quora
... The LG interactive flat panel ... Convert XML to a dict. Convert list to JSON. A well-liked Python package called Xmltodict may change your XML structure into a JSON format....
Top answer
1 of 7
86

xmltodict (full disclosure: I wrote 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"]}}'
2 of 7
27

Soviut's advice for lxml objectify is good. With a specially subclassed simplejson, you can turn an lxml objectify result into json.

import simplejson as json
import lxml

class objectJSONEncoder(json.JSONEncoder):
  """A specialized JSON encoder that can handle simple lxml objectify types
      >>> from lxml import objectify
      >>> obj = objectify.fromstring("<Book><price>1.50</price><author>W. Shakespeare</author></Book>")       
      >>> objectJSONEncoder().encode(obj)
      '{"price": 1.5, "author": "W. Shakespeare"}'       
 """


    def default(self,o):
        if isinstance(o, lxml.objectify.IntElement):
            return int(o)
        if isinstance(o, lxml.objectify.NumberElement) or isinstance(o, lxml.objectify.FloatElement):
            return float(o)
        if isinstance(o, lxml.objectify.ObjectifiedDataElement):
            return str(o)
        if hasattr(o, '__dict__'):
            #For objects with a __dict__, return the encoding of the __dict__
            return o.__dict__
        return json.JSONEncoder.default(self, o)

See the docstring for example of usage, essentially you pass the result of lxml objectify to the encode method of an instance of objectJSONEncoder

Note that Koen's point is very valid here, the solution above only works for simply nested xml and doesn't include the name of root elements. This could be fixed.

I've included this class in a gist here: http://gist.github.com/345559

🌐
GitHub
github.com › rctatman › xml-to-json
GitHub - rctatman/xml-to-json: A little Python 3 utility script to convert .xml to .json · GitHub
A little Python 3 utility script to convert .xml to .json.
Starred by 23 users
Forked by 13 users
Languages   Python
Find elsewhere
🌐
Hello Code
hellocodeclub.com › how-to-convert-xml-to-json-in-python-ultimate-guide
Hello Code - How to convert XML to JSON in Python – Step by Step guide
March 31, 2023 - To summarise, there are a few modules available in Python that allow you to convert XML to JSON. Which one you choose depends on what you are trying to achieve. If you are converting XML to JSON and don’t need to analyze or do further parsing, I will choose xmltodict, which is the lighter option.
🌐
STechies
stechies.com › converting-xml-json-using-python
Converting XML to JSON using Python
August 20, 2025 - Use connvert() function to convert your xml_data string to JSON structure.
🌐
Delft Stack
delftstack.com › home › howto › python › python xml to json
How to Convert XML to JSON in Python | Delft Stack
March 11, 2025 - Finally, we convert the dictionary to a JSON string using json.dumps() and print the result. This method provides more control over the parsing process and can be customized to handle more complex XML structures. When working with XML data, security is a significant concern, especially when dealing with untrusted sources. The defusedxml library is a great choice for safely parsing XML in Python.
🌐
Linux Hint
linuxhint.com › python_xml_to_json
Python XML to JSON
November 9, 2020 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
GitHub
github.com › eliask › xml2json
GitHub - eliask/xml2json: Convert XML to JSON with Python 3 and defusedxml or plain ElementTree
$ ./xml2json.py -h usage: xml2json.py [-h] [--unsafe] [infile] Convert an XML file to JSON. positional arguments: infile optional arguments: -h, --help show this help message and exit --unsafe do not use defusedxml: only for known-safe XML! # Normal usage for potentially unsafe XML files: pip install defusedxml ./xml2json.py sample_input.xml > sample_output.json # Without defusedxml ./xml2json.py --unsafe sample_input.xml > sample_output.json # Also supports reading from stdin: ./xml2json.py < sample_input.xml > sample_output.json
Starred by 12 users
Forked by 6 users
Languages   Python 100.0% | Python 100.0%
🌐
Java2Blog
java2blog.com › home › python › convert xml to json in python
Convert XML to JSON in python - Java2Blog
August 30, 2021 - The xtree.ElementTree.fromstring() function returns an XML string, and we use the data() function with this object to parse this string. This will return a dictionary with the required data. Then as we did earlier, we convert this dictionary to JSON using the json.dump() function...
🌐
Aspose
products.aspose.com › aspose.cells › python via java › conversion › xml to json
Convert XML to JSON in Python Excel Library - Conversion
November 13, 2025 - Add a library reference (import the library) to your Python project. Load XML file with an instance of Workbook. Convert XML to JSON by calling Workbook.save method.
🌐
Medium
amacal.medium.com › xml-to-json-in-python-f68637795b07
XML to JSON in Python - Adrian Macal - Medium
November 19, 2020 - XML to JSON in Python Having tested tools like AWS Glue + Athena, EMR and Snowflake in context their performance to query XML files, I decided to give a try very, very naive approach of converting …
🌐
PyPI
pypi.org › project › xmltojson
xmltojson
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Integrate.io
integrate.io › home › blog › conversions › how to convert xml to json: a step-by-step guide
How to Convert XML to JSON: A Step-by-Step Guide | Integrate.io
July 21, 2025 - Popular choices include Python's ‘xmltodict’ and ‘json’ libraries, JavaScript's ‘xml2js’ library, and any online JSON converter like Code Beautify. Select a tool based on your programming environment, the complexity of the XML data, and specific project needs.