Product SiteDocumentation Site

5.4. Selectors

Figure 5.27. PostfixExpr

Like in JavaScript, it is possible to navigate through data.
JSONiq supports filtering items from a sequence, looking up the value associated with a given key in an object, looking up the item at a given position in an array, and looking up all items in an array.

5.4.1. Object field selector

Figure 5.28. ObjectLookup

The simplest way to navigate in an object is similar to JavaScript, using a dot. This will work as soon as you do not push it too much: alphanumerical characters, dashes, underscores - just like unquoted keys in object constructors, any NCName is allowed.
Example 5.64. Object lookup
{ "foo" : "bar" }.foo
Result (run with Zorba):

Since JSONiq expressions are composable, you can also use any expression for the left-hand side. You might need parentheses depending on the precedence.
Example 5.65. Lookup on a single-object collection.
Result (run with Zorba):

The dot operator does an implicit mapping on the left-hand-side, i.e., it applies the lookup in turn on each item. Lookup on an object returns the value associated with the supplied key, or the empty sequence if there is none. Lookup on any item which is not an object (arrays and atomics) results in the empty sequence.
Example 5.66. Object lookup with an iteration on several objects
({ "foo" : "bar" }, { "foo" : "bar2" }, { "bar" : "foo" }).foo
Result (run with Zorba):
bar bar2

Example 5.67. Object lookup with an iteration on a collection
Result (run with Zorba):
James T. Kirk Jean-Luc Picard Benjamin Sisko Kathryn Janeway Jonathan Archer Samantha Carter

Example 5.68. Object lookup on a mixed sequence
({ "foo" : "bar1" }, [ "foo", "bar" ], { "foo" : "bar2" }, "foo").foo
Result (run with Zorba):
bar1 bar2

Of course, unquoted keys will not work for strings that are not NCNames, e.g., if the field contains a dot or begins with a digit. Then you will need quotes.
Example 5.69. Quotes for object lookup
{ "foo bar" : "bar" }."foo bar"
Result (run with Zorba):

If you use an expression on the right side of the dot, it must always have parentheses. The result of the right-hand-side expression is cast to a string. An error is raised if the cast fails.
Example 5.70. Object lookup with a nested expression
{ "foobar" : "bar" }.("foo" || "bar")
Result (run with Zorba):

Example 5.71. Object lookup with a nested expression
{ "foobar" : "bar" }.("foo", "bar")
Result (run with Zorba):
An error was raised: sequence of more than one item can not be treated as type xs:string

Example 5.72. Object lookup with a nested expression
{ "1" : "bar" }.(1)
Result (run with Zorba):

Variables, or a context item reference, do not need parentheses. Variables are introduced later, but here is a sneak peek:
Example 5.73. Object lookup with a variable
let $field := "foo" || "bar"
return { "foobar" : "bar" }.$field
Result (run with Zorba):