But even if you are only mildly interested in JSON, arrays are a welcome addition to the XQuery language, mainly because unlike sequences, arrays can be nested. I guess most XQuery programmers have encountered a situation in which it would have been nice to return a sequence of sequences from a function. And sometimes you may want to indicate that particular items in a result sequence are empty. With arrays you can do all that. Arrays may contain other arrays or maps, sequences or even the empty sequence as members.
Array constructors come in two flavors: square and curly constructors. The square constructor will look familiar to most people:
Within the square constructor, the "," is just a separator (like in a function call), so the resulting array will correspond to the comma-separated members. In the example above we're retrieving the third member using
$array(3), which is the sequence containing numbers 3 and 4. Getting the second member with
$array(2) will return the empty sequence accordingly.
The curly constructor behaves slightly different: it takes a sequence of items and creates an array member from each of them:
Above query returns "4"! See the difference? The "," in this case is the XQuery sequence constructor, so the sequence from which the array is built is 1, 3, 4.
As already announced, you can arbitrarily mix sequences, arrays and maps, resulting e.g. in:
Just like a map, an array is also a function, which accepts a single integer parameter corresponding to the position of the member to retrieve (as always in XQuery, counting starts at 1). We have seen simple examples above. For nested data structures, just chain the function calls, e.g.:
Alternatively, there's a lookup operator, which is often a bit easier to read. It works on arrays as well as maps (but not on other data types):
The lookup may also appear inside a predicate. In this case, the left hand argument (the array or map) is often skipped and defaults to the context item:
The operator expects an integer, name, parenthesized expression or a wildcard as its right hand argument. So to use e.g. a variable for the lookup, wrap it into parens:
$books is an array, the lookup argument must evaluate to a sequence of integers or you'll see an error. It is possible to look up more than one array item at a time, e.g.:
$books?(1 to 2)?title.
The wildcard returns the keys or members of a map or array. When used on a map, it results in a sequence of keys, whereas on an array, you get a sequence of members:
Use the wildcard as a quick way to iterate an array:
The XQuery 3.1 functions spec also includes a huge library of functions to process and modify arrays. All functions use the prefix
|array:size||returns the size of the array|
|array:head||returns the first member|
|array:tail||an array with all members except the first|
|array:subarray||creates an array containing a subset of members|
|array:for-each||iterate over members|
|array:filter||filter the arrays with a function|
|array:fold-left||apply function to members and collect results from left to right|
|array:fold-right||apply function to members and collect results from right to left|
|array:for-each-pair||iterate members pair-wise|
|array:append||append a member to an array|
|array:insert-before||insert new member|
|array:join||Concatenates the contents of several arrays into a single array|
As all data types in XQuery, arrays are immutable and cannot be modified. The functions above will thus always return a new array. eXist tries to implement this in an efficient way for functions like array:tail, array:append, array:subarray, array:remove without creating redundant copies.
Please note that I did not implement
array:sort yet. It will be added later.
Many of the functions mirror other functions already available in the standard function library, but take an array instead of a sequence as input. For example,
array:fold-left works like
In this example we multiply the hours required for some task by our hourly rate and return the sum.
Obviously, representing JSON data within an XQuery has become straightforward using maps and arrays. The function fn:parse-json takes a string of JSON data and returns either a map (for a JSON object), an array, an atomic value (xs:string, xs:double for numbers or xs:boolean), or the empty sequence (corresponding to
null in JSON):
Note that by default
parse-json is rather strict about the JSON syntax. For example, strings must use double quotes and duplicate keys generate an error. You can tell the function to be more relaxed about the JSON syntax by passing in a map of options:
To see the function in action on a real-world example, assume we would like to retrieve a list of commits from a git repository, using the HTTP/JSON API provided by github:
Here we're using the httpclient module to talk to the github API, which gives us more control over the communication. But there's also a simpler approach, using the
fn:json-doc retrieves the contents of the given URI and parses them using fn:parse-json. It works with external resources as well as binary documents stored in eXist. To access stored resources, just use a local path, e.g.
eXistdb has supported serialization to JSON for several years, but the old serializer was based on mapping an XML query result to JSON, which caused some difficulties at times, e.g. if you had to produce an array for a certain property, even if it was empty. Contrary to this, the new JSON output method defined by the XQuery 3.1 Serialization spec is straightforward: it takes an array, map, atomic value or empty sequence and produces valid JSON.
The JSON serializer is selected if you set the serialization option
json. This applies to both, the old and the new serializer. To distinguish between the two while preserving backwards compatibility, we use the following convention:
- if the sequence to serialize is a single XML element node, the old serializer is used
- if the sequence contains more than one item or the single item is not an XML element, it will be passed to the new serializer
This convention allows us to run all the old code unchanged without violating the 3.1 specification too much (according to the specs, a single XML element would be serialized to a JSON string).
To see the serializer in action, use the
or save the query and define the serialization method as an output option:
Other Functions Using Arrays
Some applications require calling a function dynamically without knowing the number of arguments it takes in advance. Without arrays, this had been rather difficult to solve: because sequences cannot be nested, passing arguments containing more than one item has been tricky. For example, we solved this in the templating module by using function items. The code becomes rather bloated though.
The newly added fn:apply function makes this straightforward. It takes a function item as first argument and an array containing the parameters as second:
The new features will be available in the eXistdb 2.3 release, but we encourage users to help us testing. We tried to preserve backwards compatibility with existing XQuery code, so most, if not all, apps should work as before.
Finally, I also recommend watching Dannes' presentation on Mongrel: the MongoDB extension driver for eXistdb, which will rely on the features described in this article.