Developer Documentation
Python
Updated September 19, 2026

Convert XML to JSON in Python

Parse XML and convert it to JSON using an explicit mapping convention in Python.

XML can represent attributes, mixed text, namespaces, repeated elements, and ordering in ways JSON cannot represent directly. Pick a library and a stable mapping convention, then test it with real documents.

Quick Start#

The following example uses the standard Python API or a widely used package for this task.

Using xmltodict#

Python
1# pip install xmltodict2import json3import xmltodict45value = xmltodict.parse(xml_text)6json_text = json.dumps(value, indent=, ensure_ascii=False)7print(json_text)

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Custom attribute/text keys#

Python
1value = xmltodict.parse(2    xml_text,3    attr_prefix="@",4    cdata_key="#text",5)

Important Notes#

For untrusted XML, use hardened parser guidance appropriate to your environment and disable features such as external entity resolution where applicable.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement XML → JSON in other languages: