JSON Functions

parse-json() and json-doc() read JSON text or files into maps and arrays, serialize() with the json method (Saxon 726,956 's !method=json) writes them, and json-to-xml() and xml-to-json() use the XML form:

Exporting catalog records as JSON and reading JSON back
xquery -s:booknest-catalog.xml '!method=json' '!indent=yes' -qs:'array {
  //book[position() le 2] ! map { "id": string(@id), "price": xs:decimal(.//price) } }' > books.json
cat books.json
echo '{"sku": "BN-0007", "orderId": 12345678901234567891, "note": null}' > order.json
xp 'json-doc("books.json")?*[?price gt 20]?id' 'json-doc("order.json")?orderId' \
   'json-to-xml(unparsed-text("order.json"))//*:number/string()'
Output
[
  { "price":14.99, "id":"b1" },
  { "price":39.5, "id":"b2" }
]
json-doc("books.json")?*[?price gt 20]?id => "b2"
json-doc("order.json")?orderId         => 1.2345678901234567e19
json-to-xml(unparsed-text("order.json"))//*:number/string() => "12345678901234567891"

JSON numbers become xs:double, so the order number lost digits in the map while json-to-xml() kept its text: carry long identifiers as strings. null becomes the empty sequence (test with map:contains()), key order is not kept, and 39.50 became 39.5; use format-number() when a price's text matters.


JSON Functions

In XPath 3.1, JSON data is represented using maps and arrays, and is bridged to and from XML using parse-json(), serialize(), json-to-xml(), and xml-to-json(). Native JSON support — working with JSON documents directly, without the XML round-trip shown below — is one of the major additions planned for XPath 4.0, which is under active development by the W3C's QT4CG (XQuery and XSLT 4.0 Community Group) as Community Group drafts and is not yet a W3C Recommendation.

The examples below are evaluated against:
let $m := map{"x":[1,2],"y":{"z":[10]}}
return …
map:get(parse-json(serialize($m, {"method":"json","indent":true()})),"x")[1, 2]
xml-to-json(json-to-xml(serialize($m,{"method":"json"}))){"x":[1,2],"y":{"z":[10]}}

json-doc($json_file) parses the JSON document referenced by the URI $json_file — analogous to doc() for an XML document — and returns the corresponding map or array.
ch03-json-functions.xpath.txt
merged-01-01-ch03-json-functions.xpath.txt
let $m := map{"x":[1,2],"y":{"z":[10]}}
return xml-to-json(json-to-xml(serialize($m,{"method":"json"})))
Output
{"x":[1,2],"y":{"z":[10]}}