What Do parse-json and serialize-json Do in XSLT 3.0?

XSLT 3.0 introduced native support for JSON, bridging the gap between XML workflows and modern web data formats without requiring third-party libraries. This article explains the core functions of parse-json() and serialize-json(), detailing how they convert JSON text into XPath data models—such as maps and arrays—and convert those structures back into JSON strings.

The parse-json() Function

The parse-json() function parses a JSON-formatted string and converts it into native XPath and XSLT 3.0 data structures. Instead of treating JSON as raw, unparsed text, XSLT maps JSON objects directly to XDM (XPath Data Model) maps, JSON arrays to XDM arrays, and primitive JSON values to standard XML Schema atomic types (such as xs:string, xs:double, and xs:boolean). A JSON null is represented by an empty sequence (()).

The basic signature is:

parse-json($json-text as xs:string?) as item()?

It can also accept a secondary $options map to control parsing behavior:

parse-json($json-text as xs:string?, $options as map(*)) as item()?

Common options include:

For example, parsing a JSON string like {"id": 101, "active": true} allows you to query fields directly in XPath using lookup expressions:

<xsl:variable name="data" select="parse-json($raw-json-string)"/>
<userId><xsl:value-of select="$data?id"/></userId>

The serialize-json() Function

The serialize-json() function performs the inverse operation of parse-json(). It takes an XDM item—typically a map, array, or atomic value—and serializes it into a valid JSON string.

The function signature is:

serialize-json($input as item()?) as xs:string?

Like its counterpart, serialize-json() accepts an optional parameter map to customize the output:

serialize-json($input as item()?, $options as map(*)) as xs:string?

Common serialization options include:

When transforming an XML structure into a map using XSLT, serialize-json() outputs the final structured result:

<xsl:variable name="output-map" select="map{ 'name': 'Alpha', 'count': 42 }"/>
<xsl:value-of select="serialize-json($output-map, map{ 'indent': true() })"/>

Practical Applications

Working with both functions enables several standard architectures in modern data pipelines:

  1. Consuming REST APIs: Stylesheets can retrieve JSON data via functions like unparsed-text(), parse it with parse-json(), and transform the payload directly into XML documents.
  2. Generating Web Payloads: Stylesheets can process incoming XML documents, construct XDM maps and arrays using standard templates, and emit valid JSON payloads via serialize-json().
  3. In-Flight Data Manipulation: Transforms can unpack hybrid XML documents containing embedded JSON attributes or text nodes, modify the internal data, and re-serialize the values seamlessly.