Developer Documentation
Python
Updated September 19, 2026

Convert JSON to XML in Python

Convert JSON objects to XML while making the mapping rules explicit in Python.

JSON and XML have different data models, so there is no single universal conversion. Libraries make choices about roots, arrays, attributes, text nodes, nulls, and invalid XML element names; document those choices in APIs.

Quick Start#

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

Recursive conversion with ElementTree#

Python
1import json2import xml.etree.ElementTree as ET34def append_value(parent: ET.Element, key: str, value):5    if isinstance(value, dict):6        node = ET.SubElement(parent, key)7        for child_key, child_value in value.items():8            append_value(node, child_key, child_value)9    elif isinstance(value, list):10        for item in value:11            append_value(parent, key, item)12    else:13        node = ET.SubElement(parent, key)14        node.text = "" if value is None else str(value)1516data = json.loads(source)17root = ET.Element("root")18for key, value in data.items():19    append_value(root, key, value)2021xml_text = ET.tostring(root, encoding="unicode")

Common Operations#

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

Pretty-print on modern Python#

Python
1tree = ET.ElementTree(root)2ET.indent(tree, space="  ")3xml_text = ET.tostring(root, encoding="unicode", xml_declaration=False)

Important Notes#

Define how arrays, null, booleans, and invalid XML names should map before using a converter with arbitrary JSON.

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 JSON → XML in other languages: