Recipe 12.5 · Python
Converting Between XML and JSON
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
Problem
A legacy service returns XML and the new front end wants JSON. Or the reverse: a modern API posts JSON that must be forwarded to a mainframe gateway that only accepts XML. You need a predictable conversion, and the obvious library call has a habit of changing the shape of its output depending on the data.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
SerializeXmlNode is convenient, and it hides one real flaw. An order with two <Line> elements
becomes "Line": [ ... ], while an order with one becomes "Line": { ... }. Every consumer has to
handle both shapes, and the first order with a single line breaks the front end in production.
Requirements: Python 3.12+. Install: pip install xmltodict
"""Generic XML-to-JSON conversion whose output shape depends on the data
Source: ImproveCode, Chapter 12, Recipe 12.5 "Converting Between XML and JSON"
Section: The way it's often written
Book page: 268 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Newtonsoft JsonConvert.SerializeXmlNode -> xmltodict.parse + json.dumps:
one child becomes an object, two become an array, so consumers break.
"""
# Not to copy: shape depends on the data, pulls in an extra dependency
import json
import xmltodict
def convert(xml: str) -> str:
doc = xmltodict.parse(xml)
return json.dumps(doc)
The improved recipe
Write the conversion yourself over XElement and JsonNode. It is short, uses only the base class
library, and lets the caller name the elements that are always arrays.
Usage, with Line declared as an array element:
An order with a single line now always produces this shape:
{
"Order": {
"@id": "1001",
"Customer": "Example Supply Co.",
"Line": [
{ "@sku": "A-100", "#text": "19.98" }
]
}
}
Requirements: Python 3.12+. Standard library only, nothing to install.
"""XML <-> JSON converter with "@attr", "#text" and explicitly declared arrays
Source: ImproveCode, Chapter 12, Recipe 12.5 "Converting Between XML and JSON"
Section: The improved recipe
Book page: 269-271 -- original C# listing
Converted from C# to Python.
XElement -> xml.etree.ElementTree.Element; JsonObject/JsonArray/JsonValue ->
dict/list/scalars (json module). ElementTree cannot tell <a/> from <a></a>, so
an element with no text is treated as empty (JSON null).
"""
from __future__ import annotations
import json
import xml.etree.ElementTree as ET
from collections.abc import Set
from typing import Any
JsonNode = dict[str, Any] | list[Any] | str | int | float | bool | None
# Attributes become "@name", mixed text becomes "#text".
# Element names in array_names are always written as JSON arrays.
def _local_name(tag: str) -> str:
return tag.rsplit("}", 1)[-1]
def to_json(root: ET.Element, array_names: Set[str] | None = None) -> dict[str, Any]:
array_names = array_names or set()
return {_local_name(root.tag): _convert_element(root, array_names)}
def to_xml(json_obj: dict[str, Any]) -> ET.Element:
if len(json_obj) != 1:
raise ValueError("JSON must have exactly one root property.")
(name, node), = json_obj.items()
return _build_element(name, node)
def _convert_element(element: ET.Element, array_names: Set[str]) -> JsonNode:
# ElementTree never exposes xmlns declarations as attributes.
attributes = list(element.attrib.items())
children = list(element)
value = "".join(element.itertext())
if not attributes and not children:
return None if element.text is None else value
result: dict[str, Any] = {}
for name, attr_value in attributes:
result["@" + _local_name(name)] = attr_value
groups: dict[str, list[ET.Element]] = {}
for child in children:
groups.setdefault(_local_name(child.tag), []).append(child)
for key, group in groups.items():
items = [_convert_element(e, array_names) for e in group]
result[key] = (items[0] if len(items) == 1 and key not in array_names
else items)
if not children and len(value) > 0:
result["#text"] = value
return result
def _build_element(name: str, node: JsonNode) -> ET.Element:
element = ET.Element(name)
match node:
case None:
pass
case dict():
for key, child in node.items():
_add_member(element, key, child)
case _:
element.text = _scalar_text(node)
return element
def _append_text(parent: ET.Element, text: str) -> None:
if len(parent):
last = parent[-1]
last.tail = (last.tail or "") + text
else:
parent.text = (parent.text or "") + text
def _add_member(parent: ET.Element, key: str, child: JsonNode) -> None:
if key.startswith("@"):
parent.set(key[1:], _scalar_text(child))
elif key == "#text":
_append_text(parent, _scalar_text(child))
elif isinstance(child, list):
for item in child:
parent.append(_build_element(key, item))
else:
parent.append(_build_element(key, child))
def _scalar_text(node: JsonNode) -> str:
if node is None:
return ""
if isinstance(node, str):
return node
return json.dumps(node)
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Usage: convert order XML to indented JSON with Line as an array, and back
Source: ImproveCode, Chapter 12, Recipe 12.5 "Converting Between XML and JSON"
Section: The improved recipe
Book page: 271 -- original C# listing
Converted from C# to Python.
Usage fragment wrapped in a function; converter from p269. XElement.Parse ->
ET.fromstring; ToJsonString(JsonDefaults.Indented) -> json.dumps(indent=2).
"""
from __future__ import annotations
import json
import xml.etree.ElementTree as ET
from p269_r12_5_xml_json_converter_explicit_arrays import to_json, to_xml
def round_trip(order_xml: str) -> tuple[str, ET.Element]:
arrays = {"Line"}
json_obj = to_json(ET.fromstring(order_xml), arrays)
text = json.dumps(json_obj, indent=2)
back = to_xml(json_obj)
return text, back
How it works
The conversion follows the convention most XML-to-JSON tools use, so the output looks familiar.
An element with no attributes and no children becomes a plain string. Anything else becomes an
object: attributes get an @ prefix, child elements are grouped by name, and the text of an
element that also has attributes goes under #text.
Grouping by name is what decides between a single value and an array. The arrayNames set
overrides that decision for the names you list, which removes the data-dependent shape. In
practice you know which elements repeat, usually from the partner's schema, so the list is short
and stable.
The reverse direction walks the JsonObject. Properties starting with @ become attributes,
#text becomes a text node, arrays become repeated sibling elements, and nested objects recurse.
ScalarText writes strings without quotes and other values, such as numbers and booleans, in
their JSON form.
I tested the round trip on a generated order: XML to JSON to XML produced an element that compared
equal to the original with XNode.DeepEquals.
Variations and pitfalls
- XML has no types. Every value comes out of
ToJsonas a string, including19.98. If the consumer needs numbers, deserialize the JSON into a typed DTO withJsonNumberHandling.AllowReadingFromString, whichJsonSerializerDefaults.Webalready enables. - Namespaces are dropped. The converter keeps local names only. That is usually what a JSON
consumer wants. If you must round-trip namespaces, add them back in
ToXmlwith anXNamespace. - Mixed content such as
<p>Hello <b>world</b></p>does not map cleanly to JSON with any convention. Treat it as an opaque string withelement.ToString()instead. - Often the better answer is two typed models. If you control both sides, deserialize the XML
with
XmlSerializer, map to a DTO, and serialize that withSystem.Text.Json. The generic converter earns its place for pass-through gateways and for documents with many shapes.