jsoniq

access object in an object array in jsoniq


New to JSONIQ,and using zorba what I want to do so far is to extract some information from an indexed object in an object array in JSONIQ. Here's the code so far.

    jsoniq version "1.0";
    let $bstore:={
    "bookstore":
    {
        "book":[
            {
                "category":"cooking",
                "title":"Everyday Italian",
                "author":"Giada De Laurentiis",
                "year":"2005",
                "price":"30.00"
            },
            {
                "category":"web",
                "title":"XQuery Kick Start",
                "author":["James McGovern","Per Bothner","Kurt Cagle","James Linn","Vaidyanathan Nagarajan"],
                "year":"2003",
                "price":"49.99"
            }
        ]
    }
}
for $o in $bstore.bookstore
let $a:=$o.book
return $a.title

What I'm trying to do is to return the title,author,and price of the books. I am able to return the array but whenever I type the index.

let $a:=$o.book[1].title
return $a

I get no results. My expected output would be

Everyday Italian

Any help would be much appreciated.


Solution

  • Array lookup in JSONiq is done with double square brackets, like so:

    let $a:=$o.book[[1]].title
    return $a
    

    Note, however, that the try.zorba.io page is based on an earlier version of Zorba (2.9) that doesn't support the latest version of JSONiq (it should get upgraded at some point). In this earlier version, array lookup used to be done overloading function call syntax:

    let $a:=$o.book(1).title
    return $a
    

    If you want to use the stable version of JSONiq with its up-to-date syntax, you can download Zorba 3.0 and execute queries locally.

    The semantics of [] with simple square brackets is that it filters through a sequence, either with a position or with a boolean filter, for example:

    (1, 2, 3, 4)[2]
    

    returns 2.

    An array is different from a sequence. An array can be seen as a "boxed" sequence, i.e., (1, 2, 3, 4) is a sequence of four items, but [1, 2, 3, 4] is a sequence of just one item: the array containing the nested 1, 2, 3 and 4.

    You can convert an array to a sequence with $o.book[] if needed ($o.book() with Zorba 2.9). And you can "wrap" a sequence back into an array with [ $sequence ]. It is a bit like opening, or closing a box.

    Only arrays can recursively nest, e.g., [ [1, 2], [3, 4]] has two levels of nesting, exactly as would be expected of JSON arrays. Sequences however do not nest, i.e., ((1, 2), (3, 4) is the same as the flat sequence (1, 2, 3, 4), with zero levels of nesting. Sequences of items are the primary citizen of JSONiq, and are compatible with a streaming execution (for example, filtering a sequence of millions of objects without actually materializing it).