Composing constructors

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 28. Composable array constructors

  [ 1 to 10 ]
    

Result (run with Zorba): [ 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 29. Composable object keys

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

Result (run with Zorba): { "foobar" : true }


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

Example 30. Non-atomic object keys

  { [ 1, 2 ] : true }
      

Result (run with Zorba): 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 31. Composable object values

  { "foo" : 1 + 1 }
      

Result (run with Zorba): { "foo" : 2 }


Example 32. Composable object values and automatic conversion

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

Result (run with Zorba): { "foo" : null, "bar" : [ 1, 2 ] }


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

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

Result (run with Zorba): 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 34. Merging object constructor

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

Result (run with Zorba): { "foo" : "bar", "bar" : "foo" }


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

Example 35. Merging object constructor with a type error

  {| 1 |}
      

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