XML technologies / JSON for XML professionals / Processing with Python and JavaScript

Those coming from XML often associate processing with a tree of document nodes, element nodes, attributes and text nodes. A JSON parser, by contrast, usually returns its programming language’s data structures. Python produces dictionaries and lists, for example; JavaScript produces objects and arrays. Ordinary program code operates on these values. This is not automatically easier or harder than a transformation. What matters is which operations the content model requires. [Q11]

The same task in several languages

The task is deliberately small but relevant to publishing: select available books from a catalog, sort them by ascending price and output their identifiers and titles. The price field priceCents is an integer number of euro cents in this example, not a general model covering all currencies.

File: data/catalog.json

{
  "books": [
    {
      "id": "book-001",
      "title": "Schematron",
      "available": true,
      "priceCents": 2990
    },
    {
      "id": "book-002",
      "title": "data2type Publishing APIs (Demo)",
      "available": true,
      "priceCents": 1990
    },
    {
      "id": "book-003",
      "title": "data2type Editorial Workflows (Demo)",
      "available": false,
      "priceCents": 3990
    }
  ]
}

In Python, processing consists of filtering, sorting and building new dictionaries. The source is not modified. The example parser from the preceding validation chapter is reused.

File: examples/python/catalog.py

"""Run from the package root: python examples/python/catalog.py"""
import json
from pathlib import Path
from strict_json import load_json

ROOT = Path(__file__).resolve().parents[2]

def select_books(data):
    books = [book for book in data["books"] if book["available"] is True]
    books.sort(key=lambda book: book["priceCents"])
    return [{"id": book["id"], "title": book["title"]} for book in books]

if __name__ == "__main__":
    print(json.dumps(select_books(load_json(ROOT / "data/catalog.json")),
                     ensure_ascii=False, indent=2))

The entry point can be run from the package’s root directory:

python examples/python/catalog.py

Actual generated result:

File: results/core/selected-python.json

[
  {
    "id": "book-002",
    "title": "data2type Publishing APIs (Demo)"
  },
  {
    "id": "book-001",
    "title": "Schematron"
  }
]

The same domain-specific selection in JavaScript uses filter, sort and map. Here the script runs with Node.js, not in the browser. The browser part of the package uses the same data for visible HTML output.

File: examples/js/catalog.mjs

import { readFile } from "node:fs/promises";

const url = new URL("../../data/catalog.json", import.meta.url);
const data = JSON.parse(await readFile(url, "utf8"));
const selected = data.books
  .filter(book => book.available === true)
  .sort((left, right) => left.priceCents - right.priceCents)
  .map(({ id, title }) => ({ id, title }));
console.log(JSON.stringify(selected, null, 2));

node examples/js/catalog.mjs

The tests compare the parsed result with the same expected-results file. Different indentation or object-property order does not determine domain correctness. The order of the result list does: the book costing 1,990 cents must appear first, followed by the one costing 2,990 cents.

What changes compared with XPath and templates

In XML, selection might begin with XPath book[@available = 'true']. In Python, it is a loop or comprehension over data["books"]. In JavaScript, it becomes a call to data.books.filter(...). Processing is explicitly tied to the structure of the chosen model.

A Map does not inherently know the parent node, preceding siblings or a text node’s position in the document. A custom rich-text tree can maintain this information additionally. It then belongs to that custom model and its algorithms, rather than a universally assumed JSON document structure. XML axes therefore cannot be translated simply by replacing slashes with dots.

Native integration with a programming language is convenient for form-like data and API tasks. With many mixed content types, different output modes and deep document structures, a set of template rules may remain clearer. This difference concerns the programming model, not the age of the syntax.

Reading is not yet validation

A successful parse initially confirms only that the input can be interpreted under the parser’s rules. It does not confirm that a book has a title, that available is a boolean or that an author identifier is unique. The pipeline therefore separates syntax validation, schema validation, business rules and output.

The following helper module implements a deliberately narrow input profile. It rejects duplicate object keys and non-standard numeric constants, and limits the input file size. Python’s standard module is more tolerant by default in some of these edge cases. [Q11]

File: examples/python/strict_json.py

"""A small, explicit JSON input policy for the examples."""
import json
from pathlib import Path

MAX_BYTES = 1_000_000

def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Duplicate object member: {key}")
        result[key] = value
    return result

def reject_constant(value):
    raise ValueError(f"Non-JSON numeric constant: {value}")

def load_json(path):
    path = Path(path)
    if path.stat().st_size > MAX_BYTES:
        raise ValueError("Input exceeds the example size limit")
    raw = path.read_bytes()
    if len(raw) > MAX_BYTES:
        raise ValueError("Input exceeds the example size limit")
    return json.loads(raw.decode("utf-8"),
                      object_pairs_hook=unique_object,
                      parse_constant=reject_constant)

These few rules do not replace comprehensive protection for a public upload service. Large or untrusted inputs also require limits on nesting, runtime and memory, along with controlled error responses. The one-million-byte limit is a choice made for this example, not a JSON format limit.

Output, data types and visible results

json.dumps and JSON.stringify serialize values back to JSON text. They do not produce a book page. Publication output requires another decision: populate an HTML template, build a DOM, generate an intermediate XML format or invoke a layout engine?

Mapping language values also requires care. JavaScript, for example, has undefined; JSON does not have this value. In the supplied number test, an object property with the value undefined disappears during serialization, while a property with null is retained. This difference may have domain significance when exporting a CMS form.

For prices, the second Python example uses Decimal. It demonstrates exact arithmetic and outputs the contractually agreed amount as a string. Merely switching from XML to JSON does not solve rounding problems; an explicit numeric model does.

File: examples/python/decimal_values.py

import json
from decimal import Decimal

value = json.loads('{"amount": 0.1}', parse_float=Decimal)
total = value["amount"] + Decimal("0.2")
# The exchange contract stores an exact decimal as a string.
print(json.dumps({"total": format(total, ".2f"), "currency": "EUR"}, indent=2))

File: results/core/decimal.json

{
  "total": "0.30",
  "currency": "EUR"
}

The practical rule is: read JSON, validate the domain model, transform deliberately and render the result for the output channel. An XML pipeline should maintain exactly the same separation. It is simply easier to overlook with JSON because a parser needs so little code.

back to top