JSONiq
JSONiq takes the XQuery machinery (sequences, FLWOR, functions, modules, updates) and points it at JSON. Objects and arrays become items, null becomes a value, and navigation gets a syntax that looks like JavaScript.
Two syntaxes
Zorba implements JSONiq 1.0 in two forms, and they share one data model and one function library:
- The JSONiq syntax, used for files ending in
.jq, for queries that start withjsoniq version "1.0";, and for other queries whenzorbaruns with--language jsoniq(--jsoniq). A declaration decides over the extension, and the extension over the option. It adds$o.keylookups,$a[[i]]and$a[]for arrays, the literalstrue,falseandnull, and uses$$for the context item because.is taken. - The JSONiq extension to XQuery, used in
.xqfiles. JSON constructors work as in JSONiq, but navigation is done by calling objects and arrays like functions:$o("key"),$a(1),$a(). See JSON in XQuery syntax.
Everything on the XQuery page applies to both, apart from those syntax differences. Most examples here use the JSONiq syntax.
Objects and arrays
JSON is written as JSON. Any value position can hold an expression, including a FLWOR that fills an array.
{
"name": "Zorba",
"languages": [ "XQuery", "JSONiq" ],
"embeddable": true,
"homepage": null,
"since": 2008,
"squares": [ for $i in 1 to 4 return $i * $i ],
"nested": { "empty-array": [], "empty-object": {} }
}zorba -i -r -f -q construct.jq{
"name" : "Zorba",
"languages" : [ "XQuery", "JSONiq" ],
"embeddable" : true,
"homepage" : null,
"since" : 2008,
"squares" : [ 1, 4, 9, 16 ],
"nested" : {
"empty-array" : [ ],
"empty-object" : {
}
}
}Why it matters: output is built from typed values and serialized by Zorba, so quoting and escaping cannot go wrong.
Navigation
A dot looks up a key. The key can be a name, a quoted string (for keys with spaces or symbols) or a variable. [[n]] picks the n-th member of an array, counting from 1, and [] unboxes all members into a sequence.
let $order := {
"id": 1,
"customer": { "name": "ana", "city": "Monterrey" },
"items": [ { "sku": "A1", "qty": 2 }, { "sku": "B7", "qty": 1 } ],
"ship to": "store"
}
return [
$order.customer.name,
$order.items[[2]].sku,
$order.items[].sku,
$order."ship to",
let $key := "id" return $order.$key,
count($order.items[])
]zorba -i -r -f -q navigate.jq[ "ana", "B7", "A1", "B7", "store", 1, 2 ]Why it matters: lookups apply to every item of a sequence, so $order.items[].sku walks into every item at once, like a path in XPath.
Keys, members, size
The JSONiq function library works without a prefix: keys returns the keys of an object, members the members of an array, size the number of members.
let $o := { "a": 1, "b": [ 10, 20, 30 ], "c": { "d": true } }
return {
"keys": [ keys($o) ],
"size": size($o.b),
"members": [ members($o.b) ],
"is-object": $o.c instance of object,
"sum": sum($o.b[])
}zorba -i -r -f -q keys-members.jq{
"keys" : [ "a", "b", "c" ],
"size" : 3,
"members" : [ 10, 20, 30 ],
"is-object" : true,
"sum" : 60
}Why it matters: with keys you can process objects whose keys you do not know in advance, such as dictionaries keyed by id.
The context item is $$
Inside a predicate or after the simple map operator !, the current item is $$ in JSONiq syntax.
(: In JSONiq "." is the lookup operator, so the context item is $$. :)
[
let $people := ({ "name": "ana", "age": 31 }, { "name": "luis", "age": 17 })
return (
$people[$$.age ge 18].name,
$people ! upper-case($$.name)
)
]zorba -i -r -f -q context-item.jq[ "ana", "ANA", "LUIS" ]Why it matters: code ported from XQuery needs . rewritten to $$ when it moves into a .jq file.
Loading JSON
parse-json parses a string, and unparsed-text reads a file. The sample file holds an array of orders; [] turns it into a sequence of objects.
[
{ "id": 1, "customer": "ana", "status": "shipped", "coupon": null,
"items": [ { "sku": "A1", "qty": 2, "price": 3.5 },
{ "sku": "B7", "qty": 1, "price": 12 } ] },
{ "id": 2, "customer": "luis", "status": "pending",
"items": [ { "sku": "A1", "qty": 5, "price": 3.5 } ] },
{ "id": 3, "customer": "ana", "status": "shipped", "coupon": "FALL10",
"items": [ { "sku": "C3", "qty": 1, "price": 40 } ] }
]let $orders := parse-json(unparsed-text("../data/orders.json"))[]
return [ count($orders), $orders.customer ]zorba -i -r -f -q load.jq[ 3, "ana", "luis", "ana" ]Why it matters: a sequence of objects is the JSONiq equivalent of a table, and everything else on this page works on it.
FLWOR over JSON
The FLWOR expression works on objects exactly as on nodes. Here a nested FLWOR computes each order's total.
[
for $o in parse-json(unparsed-text("../data/orders.json"))[]
let $total := sum(for $i in $o.items[] return $i.qty * $i.price)
where $o.status eq "shipped"
order by $total descending
return { "order": $o.id, "customer": $o.customer, "total": $total }
]zorba -i -r -f -q flwor.jq[ {
"order" : 3,
"customer" : "ana",
"total" : 40
}, {
"order" : 1,
"customer" : "ana",
"total" : 19
} ]Why it matters: nested arrays are handled where they are, with no flattening step or UNNEST.
Grouping
[
for $o in parse-json(unparsed-text("../data/orders.json"))[]
group by $c := $o.customer
order by $c
return {
"customer": $c,
"orders": count($o),
"skus": [ distinct-values($o.items[].sku) ]
}
]zorba -i -r -f -q group.jq[ {
"customer" : "ana",
"orders" : 2,
"skus" : [ "A1", "B7", "C3" ]
}, {
"customer" : "luis",
"orders" : 1,
"skus" : [ "A1" ]
} ]Why it matters: after group by, $o holds all orders of the customer, so $o.items[].sku collects across them.
Windows over JSON
A window clause binds a run of consecutive items to one variable, and works on objects as on any item. A sliding window starts one window at each item that meets the start condition. A tumbling window starts the next window only after the previous one ended. previous and next are empty at the ends of the input, and a condition on a missing key is false.
(: Moving average over 3 readings. A missing or null value does not count. :)
let $readings := [
{ "t": "2026-03-01T10:00:00Z", "temp": 21.5 },
{ "t": "2026-03-01T10:05:00Z", "temp": 22.5 },
{ "t": "2026-03-01T10:10:00Z" },
{ "t": "2026-03-01T10:15:00Z", "temp": null },
{ "t": "2026-03-01T10:20:00Z", "temp": 24.5 }
]
return [
for sliding window $w in $readings[]
start at $s when true
only end at $e when $e - $s eq 2
return {
"from": $w[1].t,
"avg": avg($w.temp[$$ instance of decimal])
}
]zorba -i -r -f -q window-moving-average.jq[ {
"from" : "2026-03-01T10:00:00Z",
"avg" : 22
}, {
"from" : "2026-03-01T10:05:00Z",
"avg" : 22.5
}, {
"from" : "2026-03-01T10:10:00Z",
"avg" : 24.5
} ](: Sessions: a new one after a gap above 5 minutes. Timestamps are strings in
mixed time zones; cast to xs:dateTime they compare as instants. :)
declare function local:t($e) { xs:dateTime($e.ts) };
let $events := [
{ "ts": "2026-03-01T09:00:00Z", "page": "home" },
{ "ts": "2026-03-01T10:02:00+01:00", "page": "search" },
{ "ts": "2026-03-01T09:30:00Z", "page": "home" },
{ "ts": "2026-03-01T09:31:00Z" }
]
return [
for tumbling window $w in $events[]
start $s previous $p
when empty($p) or local:t($s) - local:t($p) gt xs:dayTimeDuration("PT5M")
return {
"start": $s.ts,
"events": count($w),
"pages": [ $w.page ]
}
]zorba -i -r -f -q window-sessions.jq[ {
"start" : "2026-03-01T09:00:00Z",
"events" : 2,
"pages" : [ "home", "search" ]
}, {
"start" : "2026-03-01T09:30:00Z",
"events" : 2,
"pages" : [ "home" ]
} ](: Runs of the same state: `previous` detects each change. :)
let $log := [
{ "t": 1, "state": "ok" },
{ "t": 2, "state": "ok" },
{ "t": 3, "state": "fail", "why": "disk" },
{ "t": 4, "state": "fail" },
{ "t": 5, "state": "ok" }
]
return [
for tumbling window $w in $log[]
start $s previous $p when empty($p) or $s.state ne $p.state
return {
"state": $s.state,
"from": $s.t,
"samples": count($w)
}
]zorba -i -r -f -q window-changes.jq[ {
"state" : "ok",
"from" : 1,
"samples" : 2
}, {
"state" : "fail",
"from" : 3,
"samples" : 2
}, {
"state" : "ok",
"from" : 5,
"samples" : 1
} ]Why it matters: moving averages, sessions and change detection on irregular records take one clause, with no reshaping first.
Null and absent keys
A key can be present with the value null, or absent. A lookup of an absent key returns the empty sequence, so comparisons on it return the empty sequence too. When an object value expression returns the empty sequence, the constructor stores null; that is why the second order shows null in the first comparison.
[
for $o in parse-json(unparsed-text("../data/orders.json"))[]
return {
"id": $o.id,
"coupon is null": $o.coupon eq null,
"coupon missing": empty($o.coupon),
"coupon or default": if (empty($o.coupon) or $o.coupon eq null)
then "none" else $o.coupon
}
]zorba -i -r -f -q nulls.jq[ {
"id" : 1,
"coupon is null" : true,
"coupon missing" : false,
"coupon or default" : "none"
}, {
"id" : 2,
"coupon is null" : null,
"coupon missing" : true,
"coupon or default" : "none"
}, {
"id" : 3,
"coupon is null" : false,
"coupon missing" : false,
"coupon or default" : "FALL10"
} ]Why it matters: you decide whether "null" and "missing" mean the same thing for your data, and test for each separately when they do not.
Types
JSONiq names the JSON types directly: object, array, null, and the atomic types string, integer, boolean and so on without the xs: prefix. json-item matches objects and arrays.
[
for $v in (1, "one", true, null, [ 1 ], { "one": 1 })
return typeswitch ($v)
case object return "object"
case array return "array"
case null return "null"
case boolean return "boolean"
case string return "string"
case integer return "integer"
default return "other"
]zorba -i -r -f -q types.jq[ "integer", "string", "boolean", "null", "array", "object" ]Why it matters: heterogeneous JSON, where a field is sometimes a string and sometimes an array, is handled with one typeswitch.
Merging objects
{| ... |} merges a sequence of objects into one. Combined with a FLWOR it builds objects whose keys are computed.
let $defaults := { "color": "blue", "size": "M" }
let $override := { "size": "L", "qty": 3 }
return [
{| $override, { "color": $defaults.color } |},
{| for $k in ("x", "y") return { $k: upper-case($k) } |}
]zorba -i -r -f -q merge.jq[ {
"size" : "L",
"qty" : 3,
"color" : "blue"
}, {
"x" : "X",
"y" : "Y"
} ]Why it matters: computed keys turn a list into a dictionary in one expression.
Updates
JSONiq updates mirror the XML ones: insert json, delete json, replace value of json, rename json and append json. They follow the same rules: changes are collected and applied together, and copy/modify/return applies them to a copy.
let $order := { "id": 2, "customer": "luis", "status": "pending",
"coupon": null, "items": [ "A1" ] }
return
copy $o := $order
modify (
replace value of json $o.status with "shipped",
delete json $o.coupon,
rename json $o.customer as "client",
insert json { "carrier": "dhl" } into $o,
append json "B7" into $o.items
)
return $ozorba -i -r -f -q update.jq{
"id" : 2,
"client" : "luis",
"status" : "shipped",
"items" : [ "A1", "B7" ],
"carrier" : "dhl"
}Why it matters: JSON documents can be modified in place, in a collection or in a copy, with the same guarantees as XML updates.
JSON and XML together
JSON items and XML nodes live in the same data model, so one query can read one and produce the other. From XML to JSON, construct objects from node values:
(: From XML to JSON: build objects and arrays directly from nodes. :)
[
for $b in doc("../data/books.xml")//book
where $b/@lang = "en"
return {
"id": string($b/@id),
"title": string($b/title),
"price": xs:decimal($b/price),
"tags": [ $b/tags/tag/string() ]
}
]zorba -i -r -f -q xml-to-json.xq[ {
"id" : "b2",
"title" : "Gödel, Escher, Bach",
"price" : 24,
"tags" : [ "essay", "mathematics" ]
}, {
"id" : "b3",
"title" : "Neuromancer",
"price" : 12.99,
"tags" : [ "novel", "science fiction" ]
} ]From JSON to XML, construct elements from JSON values. This example uses XQuery syntax, where direct XML constructors are at home:
(: XQuery syntax with JSON values: call an object with a key, an array with
a position, and $a() returns all members. :)
import module namespace jn = "http://jsoniq.org/functions";
let $orders := jn:parse-json(unparsed-text("../data/orders.json"))
return
<orders>{
for $o in $orders()
return <order id="{$o("id")}" customer="{$o("customer")}">{
for $i in $o("items")()
return <item sku="{$i("sku")}" qty="{$i("qty")}"/>
}</order>
}</orders>zorba -i -r -f -q xml-mix.xq<orders>
<order id="1" customer="ana">
<item sku="A1" qty="2"/>
<item sku="B7" qty="1"/>
</order>
<order id="2" customer="luis">
<item sku="A1" qty="5"/>
</order>
<order id="3" customer="ana">
<item sku="C3" qty="1"/>
</order>
</orders>For a generic mapping that does not depend on the shape of the data, the json-xml module converts in both directions.
(: The json-xml module converts generically between the two models. :)
import module namespace jx = "http://zorba.io/modules/json-xml";
jx:json-to-xml({ "sku": "A1", "qty": 2, "tags": [ "new" ] })zorba -i -r -f -q jx-convert.xq<json xmlns="http://john.snelson.org.uk/parsing-json-into-xquery" type="object">
<pair name="sku" type="string">A1</pair>
<pair name="qty" type="number">2</pair>
<pair name="tags" type="array">
<item type="string">new</item>
</pair>
</json>Why it matters: integration work between XML systems and JSON APIs is a query, not a hand-written converter.
JSON in XQuery syntax
In .xq files the dot is part of names ($o.name would be a variable called o.name), null would be a path step, and . is the context item. So objects and arrays are called like functions, jn:null() produces null, and the JSONiq functions are called through the jn prefix, bound by importing http://jsoniq.org/functions. (Unlike in .jq files, not all of them resolve without the prefix: members does not.)
(: The same navigation in XQuery syntax (.xq): no dot lookup, no null
literal, no $$. Objects and arrays are called like functions. :)
import module namespace jn = "http://jsoniq.org/functions";
let $o := { "name": "ana", "tags": [ "a", "b", "c" ], "coupon": jn:null() }
return [
$o("name"),
$o("tags")(2),
$o("tags")(),
jn:keys($o),
jn:size($o("tags")),
$o("coupon") instance of js:null,
jn:members($o("tags")) ! upper-case(.)
]zorba -i -r -f -q xquery-syntax.xq[ "ana", "b", "a", "b", "c", "name", "tags", "coupon", 3, true, "A", "B", "C" ]Updates use the same call syntax to address the target:
copy $o := { "a": 1, "b": [ 1 ] }
modify (
replace value of json $o("a") with 2,
append json 2 into $o("b")
)
return $ozorba -i -r -f -q xquery-update.xq{
"a" : 2,
"b" : [ 1, 2 ]
}Why it matters: existing XQuery code can process JSON without switching languages.
JSONiq and XQuery 3.1
XQuery 3.1, published in 2017, solved the same problem differently: it added maps and arrays to XQuery itself. Zorba does not implement 3.1 (see what Zorba supports). If you read XQuery 3.1 code elsewhere, this table translates it.
| Task | JSONiq syntax (.jq) | Zorba XQuery (.xq) | XQuery 3.1, not in Zorba |
|---|---|---|---|
| Object or map | { "a": 1 } | { "a": 1 } | map { "a": 1 } |
| Array | [ 1, 2 ] | [ 1, 2 ] | [ 1, 2 ], array { } |
| Look up a key | $o.a | $o("a") | $o?a, $o("a") |
| Array member | $a[[1]] | $a(1) | $a?1, $a(1) |
| All members | $a[] | $a() | $a?* |
| Keys | keys($o) | jn:keys($o) | map:keys($o) |
| Array length | size($a) | jn:size($a) | array:size($a) |
| JSON null | null | jn:null() | empty sequence after parse-json |
| Parse JSON text | parse-json($s) | jn:parse-json($s) | fn:parse-json($s) |
| Change a value | replace value of json $o.a with 2 | replace value of json $o("a") with 2 | no update syntax; map:put returns a new map |
Why it matters: the concepts carry over one to one, and the main practical differences are null handling and the update syntax, which 3.1 does not have.