XML technologies / JSON for XML professionals / jq, JSONPath, Pointer and Patch

Not every processing task needs a custom Python or JavaScript program. Specialized tools are available for filtering, inspection and small conversions. From an XML perspective, some tasks resemble XPath or XQuery. The similarity lies in the task, however, not in a complete equivalence of the language models.

jq as a tool for filtering and transformations

jq processes JSON values using its own filter language. A filter can select values, create new objects, manipulate arrays and combine results. The pipeline notation is particularly useful for command-line work. jq is a tool in its own right, not a JSON processing language mandated by RFC 8259. [Q28]

The familiar catalog task is expressed in jq as follows:

File: examples/jq/select-books.jq

[.books[] | select(.available == true)]
| sort_by(.priceCents)
| map({id, title})

jq -f examples/jq/select-books.jq data/catalog.json

The actual result matches the Python and JavaScript output:

File: results/core/selected-jq.json

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

The steps can be read directly. .books selects the catalog array. map(select(...)) keeps available titles. sort_by(.priceCents) sorts the array, and the final map constructs the desired result objects. Unlike a simple path expression, this filter already defines a small transformation.

jq can also emit several result values in succession. An interface contract should therefore specify whether the result is a single array, a single object or a sequence of separate JSON texts. A tool’s ability to read an output does not automatically make that output a single JSON document.

JSONPath: path expressions for JSON

JSONPath is specified as an IETF standard in RFC 9535. Older implementations and dialects are nevertheless not automatically equivalent to that standard. A production deployment should therefore record not only the name JSONPath, but also the specific supported specification and library version. [Q08]

Available titles can be selected with the following expression:

$.books[?@.available == true].title

$ denotes the root, and @ the value currently being tested by the filter. The selection returns matches; it does not yet specify sorting by price or a complete publishing process. The following small Python file uses a library explicitly oriented toward RFC 9535. Its runtime status is recorded in the test report. [Q35]

File: examples/python/jsonpath_demo.py

"""Optional dependency: jsonpath-rfc9535."""
import json
from pathlib import Path
import jsonpath_rfc9535 as jsonpath

ROOT = Path(__file__).resolve().parents[2]
data = json.loads((ROOT / "data/catalog.json").read_text())
query = "$.books[?@.available == true].title"
print(json.dumps(jsonpath.find(query, data).values(), indent=2))

Here, the expected match order follows the input array: first Schematron, followed by data2type Publishing APIs (Demo). It therefore differs from the price-sorted output of the jq example. Selection and sorting are different tasks.

JSONPath array indices start at zero: $.books[0].title selects the first title. XPath positions, in contrast, start at one. Anyone running the same test in JavaScript, JSONPath and XPath should explicitly test this small but consequential difference.

JSON Pointer: an address rather than a query

JSON Pointer addresses a specific value in a JSON structure. This notation is useful for error messages, references and patch operations. However, it offers neither XPath-style conditions nor JSONPath filters. [Q29]

/authors/0/name
/price/amount

In the book record, the pointers point to Manuel Montero Pineda and 29.90. An empty pointer denotes the entire document. A slash within a key name is written in the pointer as ~1; a tilde is written as ~0. This substitution is a Pointer rule, not general JSON escaping.

{
  "a/b": {
    "~label": "Example"
  }
}

The appropriate pointer is /a~1b/~0label. The package tests both an ordinary author path and these two escape rules.

JSON Patch: multiple explicit operations

JSON Patch describes a sequence of operations. These include add, remove, replace, move, copy and test. The paths use JSON Pointer. For partial editorial changes, this is more precise than replacing a complete record. The application must still specify who may make changes and which version the changes apply to. [Q30]

File: data/patch.json

[
  {
    "op": "test",
    "path": "/id",
    "value": "book-001"
  },
  {
    "op": "replace",
    "path": "/title",
    "value": "Schematron (Demo metadata update)"
  },
  {
    "op": "add",
    "path": "/keywords/-",
    "value": "APIs"
  }
]

The example first checks the book identifier, then changes the title and appends a new value to the keywords array using -. Checking the identifier is a plausibility check. It does not automatically detect every concurrent change to another field. For that, the interface contract needs an additional version check, for example.

File: examples/python/patch_demo.py

"""Optional dependency: jsonpatch. The original input is not mutated."""
import json
from pathlib import Path
import jsonpatch

ROOT = Path(__file__).resolve().parents[2]
data = json.loads((ROOT / "data/book.json").read_text())
patch = json.loads((ROOT / "data/patch.json").read_text())
result = jsonpatch.apply_patch(data, patch, in_place=False)
print(json.dumps(result, indent=2))

The expected output contains the title Schematron (Demo metadata update) and the additional keyword APIs. This is a deliberate change to a test copy, not an actual different book title or a claim about a new edition. The prepared library example is marked as passed only when the patch library is actually available and the comparison has run successfully.

JSON Merge Patch: compact, but with different null behavior

JSON Merge Patch takes a different approach. An object describes properties to add or replace. A property with null means that the corresponding property is removed from the target object. Arrays are replaced as a whole, not merged by position. [Q31]

File: data/merge-patch.json

{
  "subtitle": null,
  "keywords": [
    "XML",
    "JSON",
    "APIs"
  ]
}

In the executed example, subtitle disappears from the result: the null value in the patch removes the subtitle that was previously present. It is not stored as a new field value. The keywords array is replaced in its entirety. These semantics must not be confused with the meaning of null in an ordinary book record.

File: examples/python/merge_patch.py

"""JSON Merge Patch. Null removes an object member; arrays are replaced."""
from copy import deepcopy

def merge_patch(target, patch):
    if not isinstance(patch, dict):
        return deepcopy(patch)
    result = deepcopy(target) if isinstance(target, dict) else {}
    for key, value in patch.items():
        if value is None:
            result.pop(key, None)
        else:
            result[key] = merge_patch(result.get(key), value)
    return result

An interface that must distinguish between setting an explicit null value and removing a property should work through that distinction before choosing a patch method. Shorter notation is not automatically a better fit for the business requirements.

Many records: JSON Lines and NDJSON

For line-oriented transfer and batch processing, a complete JSON value is often written on each physical line. The package uses records.jsonl; the NDJSON specification likewise describes a line-oriented JSON format. Such files are not the same as a single JSON array. Line breaks within strings must be represented by escape sequences. [Q36]

File: data/records.jsonl

{"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}

import json
from pathlib import Path

with Path("data/records.jsonl").open(encoding="utf-8") as source:
    for line_number, line in enumerate(source, start=1):
        if not line.strip():
            raise ValueError(f"Empty record at line {line_number}")
        record = json.loads(line)
        print(record["id"], record["title"])

The advantage is that individual records can be processed without first building a complete array. However, this does not automatically make a multi-page chapter with nested mixed content easy to stream. The data model, record boundaries and required global rules remain crucial.

back to top