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
Top answer
1 of 3
10

Many Python XML libraries support parsing XML sub elements incrementally, e.g. xml.etree.ElementTree.iterparse and xml.sax.parse in the standard library. These functions are usually called "XML Stream Parser".

The xmltodict library you used also has a streaming mode. I think it may solve your problem

https://github.com/martinblech/xmltodict#streaming-mode

2 of 3
4

Instead of trying to read the file in one go and then process it, you want to read it in chunks and process each chunk as it's loaded. This is a fairly common situation when processing large XML files and is covered by the Simple API for XML (SAX) standard, which specifies a callback API for parsing XML streams - it's part of the Python standard library under xml.sax.parse and xml.etree.ETree as mentioned above.

Here's a quick XML to JSON converter:

from collections import defaultdict
import json
import xml.etree.ElementTree as ET

def parse_xml(file_name):
    events = ("start", "end")
    context = ET.iterparse(file_name, events=events)

    return pt(context)

def pt(context, cur_elem=None):
    items = defaultdict(list)

    if cur_elem:
        items.update(cur_elem.attrib)

    text = ""

    for action, elem in context:
        # print("{0:>6} : {1:20} {2:20} '{3}'".format(action, elem.tag, elem.attrib, str(elem.text).strip()))

        if action == "start":
            items[elem.tag].append(pt(context, elem))
        elif action == "end":
            text = elem.text.strip() if elem.text else ""
            elem.clear()
            break

    if len(items) == 0:
        return text

    return { k: v[0] if len(v) == 1 else v for k, v in items.items() }

if __name__ == "__main__":
    json_data = parse_xml("large.xml")
    print(json.dumps(json_data, indent=2))

If you're looking at a lot of XML processing check out the lxml library, it's got a ton of useful stuff over and above the standard modules, while also being much easier to use.

http://lxml.de/tutorial.html

Discussions

Convert JSON to XML in Python - Stack Overflow
I see a number of questions on SO asking about ways to convert XML to JSON, but I'm interested in going the other way. Is there a python library for converting JSON to XML? Edit: Nothing came back ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to convert XML to JSON in Python? - Stack Overflow
Possible Duplicate: Converting XML to JSON using Python? I'm doing some work on App Engine and I need to convert an XML document being retrieved from a remote server into an equivalent JSON obj... More on stackoverflow.com
๐ŸŒ stackoverflow.com
It's 2025. What's your favorite module or method for converting xml to json and vice versa?
I hate working with XML. I recently had to parse some responses from namecheap and just used ElementTree (xml.etree.ElementTree). I didn't find any recent XML to JSON modules, and my need was minimal, so just stuck to ET. I would hate to have to work with XML regularly! More on reddit.com
๐ŸŒ r/learnpython
12
6
March 18, 2025
Convert XML to Json
if you can at least use the standard python libraries you can parse the xml with the builtin ElementTree , it's not as good as lxml but it should work More on reddit.com
๐ŸŒ r/sysadmin
6
1
September 6, 2024
People also ask

Can I convert complex XML structures to JSON seamlessly?
Converting complex XML structures to JSON can be challenging due to nested elements and attributes. However, with the right tools and careful handling, it is possible to achieve a seamless conversion. Tools like โ€˜xmltodictโ€™ in Python can help manage these complexities by correctly mapping XML elements to JSON objects and arrays.
๐ŸŒ
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
What are the advantages of using JSON over XML?
JSON offers several advantages over XML, including a more compact and readable format, faster parsing and generation, and better performance in web applications. JSON's structure, which uses key-value pairs and arrays, makes it easier to work with in modern programming environments and facilitates efficient data interchange.
๐ŸŒ
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
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-xml-to-json-dict
Python XML to JSON, XML to Dict | DigitalOcean
August 3, 2022 - Today we will learn how to convert XML to JSON and XML to Dict in python. We can use python xmltodict module to read XML file and convert it to Dict or JSON data. We can also stream over large XML files and convert them to Dictionary.
๐ŸŒ
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-xml-to-json
Python - XML to JSON - GeeksforGeeks
April 28, 2025 - # Program to convert an xml # file to json file # import json module and xmltodict # module provided by python import json import xmltodict # open the input xml file and read # data in form of python dictionary # using xmltodict module with open("test.xml") as xml_file: data_dict = xmltodict.parse(xml_file.read()) # xml_file.close() # generate the object using json.dumps() # corresponding to json data json_data = json.dumps(data_dict) # Write the json data to output # json file with open("data.json", "w") as json_file: json_file.write(json_data) # json_file.close()
๐ŸŒ
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 - This assessment helps plan the conversion process and anticipate potential challenges, such as handling deeply nested structures or large datasets. The next step involves identifying appropriate tools and libraries for the conversion. Popular choices include Python's โ€˜xmltodictโ€™ and โ€˜jsonโ€™ libraries, JavaScript's โ€˜xml2jsโ€™ library, and any online JSON converter like Code Beautify.
Find elsewhere
๐ŸŒ
Quora
quora.com โ€บ How-can-I-convert-XML-to-JSON-in-Python
How to convert XML to JSON in Python - Quora
For large files, use iterparse and streaming JSON output. For strict or schema-based needs, use xmlschema or lxml and write a custom mapper that documents attribute/text handling.
๐ŸŒ
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.
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

๐ŸŒ
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 โ€บ 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
๐ŸŒ
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%
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python xml to json
How to Convert XML to JSON in Python | Delft Stack
March 11, 2025 - This tutorial demonstrates how to convert XML data to JSON format in Python. Explore various methods using libraries like xmltodict, ElementTree, and defusedxml to efficiently handle XML data conversion. Enhance your programming skills and learn best practices for working with different data formats.
๐ŸŒ
MicroPyramid
micropyramid.com โ€บ blog โ€บ how-to-convert-xml-content-into-json-using-xmltodict
How to Convert XML Content into Json Using XMLtodict | MicroPyramid
>>> import xmltodict >>> import json >>> json.loads(json.dumps(xmltodict.parse(''' <root> <persons city="hyderabad"> <person name="abc"> <name age="50" mobile="789" /> </person> </persons> <persons city="vizag"> <person name="xyz"> <name age="70" mobile="123" /> </person> </persons> </root> ''', process_namespaces=True))) >>> mydict = {u'root': {u'persons': [{u'@city': u'hyderabad', u'person': {u'@name': u'abc', u'name': {u'@mobile': u'789', u'@age': u'50'}}}, {u'@city': u'vizag', u'person': {u'@name': u'xyz', u'name': {u'@mobile': u'123', u'@age': u'70'}}}]}} >>> print xmltodict.unparse(mydict, pretty=True)
๐ŸŒ
Medium
amacal.medium.com โ€บ xml-to-json-in-python-f68637795b07
XML to JSON in Python - Adrian Macal - Medium
November 19, 2020 - I converted 35GB of XML into 19GB of JSON in 19 minutes on c5.2xlarge machine. The bottleneck was CPU. It means it can be either optimized or distributed.
๐ŸŒ
The Daily Signal
lowrey.me โ€บ use-pythons-xmltodict-to-convert-xml-to-json
Use Python's xmltodict to convert XML to JSON
April 23, 2018 - Essentially, give it an XML document and it gives you a native Python dictionary with intuitive mappings for XML specific features like attributes and namespaces. For example, lists in the form of <item>1</item><item>2</item><item>3</item> simply become item: [1, 2, 3]. Once it is in Python's dictionary model, it is trivial to get it to convert to JSON due to their similarity.
๐ŸŒ
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 - Aspose Excel. This comprehensive solution provides Python developers with a fully integrated approach to convert XML to JSON format, enabling seamless saving of XML data into JSON format using the Aspose.Cells library, all through efficient and customizable Python code.
๐ŸŒ
Plajjan
plajjan.github.io โ€บ 2020-01-29-convert-xml-to-json-and-yaml.html
Convert XML to JSON
January 29, 2020 - However, as the encoding of data in YAML has the same concepts as JSON, it is trivial to convert from JSON to YAML or vice versa with standard tools. Here is an example Python script that will do the conversion: #!/usr/bin/env python3 import json import sys import yaml jf = open(sys.argv[1]) print(yaml.dump(json.load(jf))) ... #!/usr/bin/env python3 import json import sys import yaml yf = open(sys.argv[1]) print(json.dumps(yaml.load(yf))) To use it, we pipe the output from our XML to JSON conversion on to the Python script that does JSON to YAML conversion.