XML technologies / JSON for XML professionals / Processing JSON with XQuery

XQuery 3.1 combines querying XML nodes with maps and arrays. This allows JSON inputs to be processed in a language environment familiar to many XML developers. It is particularly useful for selection, restructuring and combining data. The familiar FLWOR logic remains; only the input values and result construction change. [Q05]

The catalog query as a FLWOR expression

The following XQuery program reads the JSON catalog, selects available books, sorts by price and creates an array of reduced book objects.

File: examples/xquery/select-books.xq

xquery version "3.1";
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare option output:method "json";
declare option output:indent "yes";
declare variable $input-uri external;
array {
  for $book in json-doc($input-uri)?books?*
  where $book?available = true()
  order by $book?priceCents
  return map { "id": $book?id, "title": $book?title }
}

The correspondence to an XML query is immediately apparent. for iterates over the book values, where filters, order by sorts and return constructs the result. The book values here are maps; ?title is therefore a lookup, not an element test.

The expected output is the same as with Python, JavaScript and jq:

File: expected/selected-books.json

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

The outer array constructor is essential. An XQuery sequence and a JSON array are not the same. An API contract that always requires a list must produce an array even for zero or exactly one match. The number of matches must not silently change the result type.

XML inputs as a JSON result

The XML-input variant reads element nodes but constructs the same JSON-oriented target structure.

File: examples/xquery/xml-to-json.xq

xquery version "3.1";
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare option output:method "json";
declare variable $input-uri external;
map {
  "books": array {
    for $book in doc($input-uri)/catalog/book
    return map {
      "id": string($book/@id),
      "title": string($book/title),
      "available": xs:boolean($book/@available),
      "priceCents": xs:integer($book/@priceCents)
    }
  }
}

The explicit casts show the boundary between the models. An attribute is initially a node or a value derived from it. A JSON boolean, however, must not be output as the string "true". Likewise, an amount in cents should be a number and should not inadvertently remain text.

This approach suits an API projection from an existing XML collection. The complete article can remain in XML while an XQuery query produces search results, catalog cards or structured metadata for a web service. Changing the output format does not force a change to the editorial master format.

Distinguishing null from missing properties

One particularly important bridging rule concerns JSON null. In the JSON-to-XDM mapping, it is represented as an empty sequence. Looking up a missing map Map entry also returns an empty sequence. Testing only empty($book?subtitle) therefore cannot distinguish the two situations. [Q26]

File: examples/xquery/null-vs-missing.xq

xquery version "3.1";
declare namespace map = "http://www.w3.org/2005/xpath-functions/map";
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare option output:method "json";
let $data := parse-json('{"subtitle":null,"authors":[]}')
return map {
  "subtitleExists": map:contains($data, "subtitle"),
  "subtitleValueIsEmpty": empty($data?subtitle),
  "missingExists": map:contains($data, "missing"),
  "missingValueIsEmpty": empty($data?missing),
  "authorsIsArray": $data?authors instance of array(*)
}

Expected output:

File: expected/null-vs-missing.json

{
  "subtitleExists": true,
  "subtitleValueIsEmpty": true,
  "missingExists": false,
  "missingValueIsEmpty": true,
  "authorsIsArray": true
}

map:contains answers whether the property exists at all. Accessing the value answers a different question. An empty array, in turn, is an array value without members, not the same as an empty sequence. This distinction is central to data cleaning, merge procedures and optional CMS fields.

Arrays, sequences and position counting

The notations array { ... } and [ ... ] look similar but handle sequences differently. An array can have members whose values are themselves sequences. When mapping to JSON, the JSON serializer’s rules apply. [Q05] [Q27]

File: examples/xquery/arrays-and-sequences.xq

xquery version "3.1";
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare option output:method "json";
map {
  "emptyArray": array {},
  "singletonArray": array { "one" },
  "twoMembers": array { "one", "two" },
  "arrayContainingNull": [()],
  "emptySequenceValue": ()
}

The documented expectation is:

File: expected/arrays-and-sequences.json

{
  "emptyArray": [],
  "singletonArray": [
    "one"
  ],
  "twoMembers": [
    "one",
    "two"
  ],
  "arrayContainingNull": [
    null
  ],
  "emptySequenceValue": null
}

array { () } creates an array without members. [()] instead creates an array with one member whose value is the empty sequence; JSON output turns this into a null value. The example therefore treats the two cases separately.

Position counting also differs from JavaScript and JSONPath. In an XPath/XQuery array, ?1 denotes the first member. In JavaScript, access is written [0], and likewise in JSONPath [0]. Object and map lookups, however, use key names, not numeric positions.

Another edge case arises when unpacking with ?*. Array members become accessible as a sequence. Members containing an empty sequence contribute no Item. In an array read from JSON and containing null values, this can lose positional information if a new array is then carelessly built from the items. A position-preserving reconstruction must explicitly account for the number of members and each member position.

Not every XDM structure is automatically JSON

XDM offers more than the JSON data model. A map can, for example, have keys of other atomic types, and sequences can contain multiple items. Functions and arbitrary internal data structures cannot readily be output as meaningful domain-specific JSON values. The JSON serializer has specific rules and error cases for this. [Q27]

In practice, an explicit JSON target structure is recommended: string keys, deliberately chosen numeric and boolean values, arrays for lists and documented null handling. The serializer should serialize that structure, not compensate for missing modeling decisions.

The prepared XQuery tests use SaxonC as a replaceable reference runtime. The files remain XQuery 3.1 examples; with another processor, check startup parameters, URI resolution, packaging and supported options separately. Nor must one XML database necessarily support every JSON storage or indexing behavior of another XML database. [Q32]

back to top