Construction of items

In JSONiq, objects, arrays and basic atomic values (string, number, boolean, null) are constructed exactly as they are constructed in JSON. Any JSON document is also a valid JSONiq query which just "returns itself".

Because JSONiq expressions are fully composable, however, in objects and arrays constructors, it is possible to put any JSONiq expression and not only atomic literals, object constructors and array constructors. Furthermore, JSONiq supports the construction of other W3C-standardized builtin types (date, hexBinary, etc).

The following examples are a few of many operators available in JSONiq: "to" for creating arithmetic sequences, "||" for concatenating strings, "+" for adding numbers, "," for appending sequences.

In an array, the operand expression will evaluated to a sequence of items, and these items will be copied and become members of the newly created array.

Example 8. Composable array constructors

  [ 1 to 10 ]
    

Result: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]


In an object, the expression you use for the key must evaluate to an atomic - if it is not a string, it will just be cast to it.

Example 9. Composable object keys

  { "foo" || "bar" : true }
      

Result: { "foobar" : true }


An error is raised if the key expressions is not an atomic.

Example 10. Non-atomic object keys

  { [ 1, 2 ] : true }
      

Result: An error was raised: can not atomize an array item: an array has probably been passed where an atomic value is expected (e.g., as a key, or to a function expecting an atomic item)


If the value expression is empty, null will be used as a value, and if it contains two items or more, they will be wrapped into an array.

If the colon is preceded with a question mark, then the pair will be omitted if the value expression evaluates to the empty sequence.

Example 11. Composable object values

  { "foo" : 1 + 1 }
      

Result: { "foo" : 2 }


Example 12. Composable object values and automatic conversion

  { "foo" : (), "bar" : (1, 2) }
      

Result: { "foo" : null, "bar" : [ 1, 2 ] }


Example 13. Optional pair (not implemented yet in Zorba)

  { "foo" ?: (), "bar" : (1, 2) }
      

Result: An error was raised: invalid expression: syntax error, unexpected "?", expecting "end of file" or "," or "}"


The {| |} syntax can be used to merge several objects.

Example 14. Merging object constructor

  {| { "foo" : "bar" }, { "bar" : "foo" } |}
      

Result: { "foo" : "bar", "bar" : "foo" }


An error is raised if the operand expression does not evaluate to a sequence of objects.

Example 15. Merging object constructor with a type error

  {| 1 |}
      

Result: An error was raised: xs:integer can not be treated as type object()*