Two of the most popular data exchange formats for structured data on the internet today are XML and JSON.
JSON (pronounced 'Jason' ) stands for JavaScript Object Notation.
Like XML, JSON is a human readable text format, but JSON is lightweight and requires less overhead than XML.
To facilitate interoperability, XQuery version 3.1 introduces support for consuming JSON data.
In addition, XQuery 3.1 introduces support for maps and arrays allowing for a more natural representation of JSON data in XQuery expressions.
Both maps and arrays have been covered extensively in the XPath 3.0 and 3.1 training: see Maps and Arrays
XQuery 3.1 provides two built-in functions which are used to parse JSON data:
The parse-json() function parses a string supplied in JSON format and typically returns a map or array.
parse-json() has two signatures:
example: Parsing a basic json string which returns a map
let $j := parse-json( ' { "name": "mike" , "age": 34 , "department": "accounting" } ' ) return <age> { $j?age } </age>
<age>34</age>
example: Parsing a json string which returns a map containing a nested map
let $j := parse-json( ' { "employee": { "name": "mike" , "age": 34 , "department": "accounting" } } ' ) return <age> { $j?employee?age } </age>
<age>34</age>
example: Parsing a json string which returns a map containing nested maps and arrays
let $j := parse-json( ' { "employees": { "employee": [{ "name": "mike" , "age": 34 , "department": "accounting" },{ "name": "sally" , "age": 24 , "department": "sales" }] } } ' ) let $s := array:size( $j?employees?employee ) for $i in (1 to $s) return <age> { $j?employees?employee($i)?age } </age>
<age>34</age> <age>24</age>
The json-doc() function parses an external resource containing JSON and typically returns a map or array.
json-doc() has two signatures:
example: Parsing an external json resource which returns a simple map
let $j := json-doc( 'https://qrng.anu.edu.au/API/jsonI.php?length=1&type=uint8' ) return <random> { $j?data } </random>
<random>200</random>