XML technologies / JSON for XML professionals / Mixed content and rich text
JSON can look very compact for a simple metadata record. The picture changes for a paragraph containing inline markup. This is precisely where publishing users should look closely: a paragraph is not just a collection of fields, but an ordered sequence of text and markup. It must remain editable, transformable and understandable in meaning.
One paragraph, three possible JSON strategies
The XML example contains ordinary text, emphasis and a cross-reference:
File: data/mixed.xml
<p>Manuel Montero Pineda explains <em>Schematron</em> at data2type.
See <xref target="chapter-2">the workflow</xref>.</p>The first JSON strategy stores only the visible text:
{
"text": "Manuel Montero Pineda explains Schematron at data2type. See the workflow."
}That may suffice for a search index. For an editorial master file, it is insufficient in this example because the emphasis and reference target disappear. The conversion would succeed technically while deliberately losing domain information.
The second strategy stores the markup as a string:
{
"html": "<p>Manuel Montero Pineda explains <em>Schematron</em> at data2type.
See <a href=\"#chapter-2\">the workflow</a>.</p>"
}This is valid JSON and is often useful for delivering HTML that has already been rendered. However, the document model now resides inside the string. A JSONPath expression can select the html field, but cannot navigate its markup without further processing. The security of the HTML output must also be assessed separately.
The third strategy models the document structure explicitly. This package uses a small, custom abstract syntax tree, or AST, for that purpose:
File: data/rich-text.json
{
"type": "paragraph",
"children": [
{
"type": "text",
"value": "Manuel Montero Pineda explains "
},
{
"type": "emphasis",
"children": [
{
"type": "text",
"value": "Schematron"
}
]
},
{
"type": "text",
"value": " at data2type. See "
},
{
"type": "xref",
"target": "chapter-2",
"children": [
{
"type": "text",
"value": "the workflow"
}
]
},
{
"type": "text",
"value": "."
}
]
}The array children preserves the order. Text is a node type of its own; the cross-reference has an explicit target. The JSON notation becomes more verbose, but the structure remains accessible to software. The description “custom” is important: paragraph, emphasis, xref and children are not reserved JSON words.
What a rich-text model actually needs to support
The small AST suffices for this example, not for an arbitrary publishing collection. A production model must decide, among other things, how to describe paragraphs, lists, tables, footnotes, formulas, language changes, revisions and references. A table involves not just rows and cells, but potentially also merged cells, headers, captions and the relationship between table structure and accessibility.
JSON does not prevent such models. It simply supplies fewer document-oriented building blocks, leaving these decisions to the application vocabulary. An XML vocabulary can make equally poor choices. A fair comparison therefore asks whether the two specific content models being considered meet the same requirements.
Contentful provides a real JSON-based rich-text model. Its content consists of nodes with fields such as nodeType, data and, depending on the node type, content, value or marks. Linked entries and media are treated as references that must be resolved during output. [Q18]
A synthetic representation of the shorter paragraph, based on this structure, looks like this:
File: data/contentful-style.json
{
"nodeType": "document",
"data": {},
"content": [
{
"nodeType": "paragraph",
"data": {},
"content": [
{
"nodeType": "text",
"value": "Manuel Montero Pineda explains ",
"marks": [],
"data": {}
},
{
"nodeType": "text",
"value": "Schematron",
"marks": [
{
"type": "italic"
}
],
"data": {}
},
{
"nodeType": "text",
"value": " at data2type.",
"marks": [],
"data": {}
}
]
}
]
}Here, italics are modeled as a mark on a text node. Our own AST instead uses a containing emphasis node. Both forms can produce the same display, but are not automatically interchangeable. Exporting between the models requires explicit rules and tests.
Processing: from the tree to visible output
The Python renderer in the package allows only the defined node types. It escapes text and creates cross-references only as local fragment references:
File: examples/python/render_rich.py
"""Whitelist rendering. Validate the AST before calling this function."""
from html import escape
from urllib.parse import quote
def render(node):
kind = node["type"]
if kind == "text":
return escape(node["value"], quote=False)
if kind not in {"paragraph", "emphasis", "xref"}:
raise ValueError(f"Unsupported node type: {kind}")
body = "".join(render(child) for child in node["children"])
if kind == "xref":
target = quote(node["target"], safe="")
return f'<a href="#{target}">{body}</a>'
tag = {"paragraph": "p", "emphasis": "em"}[kind]
return f"<{tag}>{body}</{tag}>"The generated HTML output is:
File: results/core/rich-text.html
<p>Manuel Montero Pineda explains <em>Schematron</em> at data2type.
See <a href="#chapter-2">the workflow</a>.</p>In the browser, the same output looks like this:

A second implementation creates the DOM nodes directly in the browser. It uses createTextNode() and createElement(), rather than passing uncontrolled strings to innerHTML:
File: examples/js/richtext.mjs
// Browser DOM renderer for the documented example AST.
export function renderNode(node, document) {
if (node.type === "text") return document.createTextNode(node.value);
const tags = { paragraph: "p", emphasis: "em", xref: "a" };
if (!Object.hasOwn(tags, node.type)) {
throw new Error(`Unsupported node type: ${node.type}`);
}
const element = document.createElement(tags[node.type]);
if (node.type === "xref") {
element.setAttribute("href", "#" + encodeURIComponent(node.target));
}
for (const child of node.children) element.append(renderNode(child, document));
return element;
}This is not yet a universal sanitizer or a renderer for external CMS formats. It is a deliberately small, understandable implementation for the documented AST. The test run checks its structure and allowed node types before output. The browser demonstration then loads this validated local fixture; it does not implement its own complete JSON Schema validator. An unknown type is treated as an error, not silently omitted.
Round-tripping and easily overlooked whitespace
The package includes a real reverse conversion for the subset p, em and xref. When implementing this with lxml it is particularly important that text before a child node can be stored in .text and text after it in .tail. Reading only .text loses parts of the paragraph.
File: examples/python/mixed_content.py
"""Round-trip for the documented p/em/xref subset, not arbitrary XML."""
from lxml import etree
TO_TYPE = {"p": "paragraph", "em": "emphasis", "xref": "xref"}
TO_TAG = {value: key for key, value in TO_TYPE.items()}
def parse_xml(path):
parser = etree.XMLParser(resolve_entities=False, load_dtd=False,
no_network=True, remove_blank_text=False)
tree = etree.parse(str(path), parser)
if tree.docinfo.doctype:
raise ValueError("DOCTYPE is outside the example profile")
return tree.getroot()
def to_ast(element):
if element.tag not in TO_TYPE:
raise ValueError(f"Unsupported XML node: {element.tag}")
allowed = {"target"} if element.tag == "xref" else set()
if set(element.attrib) - allowed:
raise ValueError("Unsupported attributes")
result = {"type": TO_TYPE[element.tag], "children": []}
if element.tag == "xref":
result["target"] = element.attrib["target"]
if element.text:
result["children"].append({"type": "text", "value": element.text})
for child in element:
result["children"].append(to_ast(child))
if child.tail:
result["children"].append({"type": "text", "value": child.tail})
return result
def from_ast(node):
if node["type"] not in TO_TAG:
raise ValueError("Unsupported rich-text node")
element = etree.Element(TO_TAG[node["type"]])
if node["type"] == "xref":
element.set("target", node["target"])
previous = None
for child in node["children"]:
if child["type"] == "text":
if previous is None:
element.text = (element.text or "") + child["value"]
else:
previous.tail = (previous.tail or "") + child["value"]
else:
previous = from_ast(child)
element.append(previous)
return elementThe test checks the AST generated from XML against the JSON file and then converts it back. For the documented subset, it compares the canonicalized XML structure. The claim is deliberately limited: comments, processing instructions, DTDs, arbitrary namespaces or unknown attributes are not claimed to be preserved universally. Unsupported structures cause an error.
Even apparently harmless whitespace cleanup can be wrong here. Between Manuel Montero Pineda explains and Schematron and before before publishing the spaces form part of the text. Pretty-printing and indentation must not be confused with normalization that is legitimate for the domain. For a publishing round-trip, this is a required test case.