Construction of items

This will not come as a surprise since JSONiq is tailor-made: objects, arrays and atomic values are constructed... exactly as they are constructed in JSON. Any JSON document is also a valid JSONiq query which just "returns itself".

Of course, JSONiq would not be very interesting if all you could do is copy and paste JSON documents.

Because JSONiq expressions are fully composable, in objects and arrays constructors, you can put way more than just atomic literals, object constructors and array constructors: you can put any JSONiq expression.

The following examples are just a few of many operators you can use: "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)


And do not worry about the value expression: if it is 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()*