Object field selector

Figure 44. ObjectLookup

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 77. Object lookup

{ "foo" : "bar" }.foo
      

Result (run with Zorba): bar


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 78. Lookup on a single-object collection.

collection("one-object").foo
      

Result (run with Zorba): bar


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 79. Object lookup with an iteration on several objects

({ "foo" : "bar" }, { "foo" : "bar2" }, { "bar" : "foo" }).foo
        

Result (run with Zorba): bar bar2


Example 80. Object lookup with an iteration on a collection

collection("captains").name
      

Result (run with Zorba): James T. Kirk Jean-Luc Picard Benjamin Sisko Kathryn Janeway Jonathan Archer Samantha Carter


Example 81. 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 82. Quotes for object lookup

{ "foo bar" : "bar" }."foo bar"
      

Result (run with Zorba): bar


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 83. Object lookup with a nested expression

{ "foobar" : "bar" }.("foo" || "bar")
      

Result (run with Zorba): bar


Example 84. 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 85. Object lookup with a nested expression

{ "1" : "bar" }.(1)
      

Result (run with Zorba): bar


Variables, or a context item reference, do not need parentheses. Variables are introduced later, but here is a sneak peek:

Example 86. Object lookup with a variable

let $field := "foo" || "bar"
return { "foobar" : "bar" }.$field
      

Result (run with Zorba): bar