Search code examples
javascriptjsonxqueryjsoniq

Using Jsoniq to display some of the string in json


Can you guys teach me on how to use jsoniq to display both of the book name which is robin cruose and tom jones? i've gone through some research but no matter how i do, it's always wrong.

{
   "books": {
      "reader": {
         "Read": {
            "book": {
               "name": "Robinson Crusoe",
               "author": "Daniel Defoe"
            }
         },
         "HaventRead": {
            "book": {
               "name": " Tom Jones",
               "author": "Henry Fielding "
            }
         },
         "_type": "Ken Rawing"
      }
   }
}

This is how i did in zorba.io and it got lots of error, i am very sure the way i did is totally wrong. Please teach me

for $reader in collection("books"),
$read in collection("books"),
$book in collection ("books")
where $reader.type eq "Ken Rawing"
return $book


Solution

  • Getting some leaf values from a JSON document is done with the navigation syntax, which is the . notation.

    It doesn't need a for clause, as iteration is implicit with the ..

    Assuming the object is stored in the variable $content, $content.books.reader navigates to the object with the fields Read and HaventRead. Calling jnlib:values() then gets the two objects in there, and then one continues all the way to the name with .book.name.

    The query is like so (most of it is actually the input document itself, which is typically stored in a file or a data store instead):

    jsoniq version "1.0";
    
    import module namespace jnlib = "http://jsoniq.org/function-library";
    
    (: That's the input document, stored in a global variable :)
    declare variable $content := {
       "books": {
          "reader": {
             "Read": {
                "book": {
                   "name": "Robinson Crusoe",
                   "author": "Daniel Defoe"
                }
             },
             "HaventRead": {
                "book": {
                   "name": " Tom Jones",
                   "author": "Henry Fielding "
                }
             },
             "_type": "Ken Rawing"
          }
       }
    };
    
    (: That's the query :)
    jnlib:values($content.books.reader).book.name
    

    Mind the jsoniq version="1.0";, which activates the native JSONiq parser (the default parser on try.zorba.io is XQuery).

    It can also be tested in zorba.io

    Note

    JSONiq also exists as an extension to XQuery, in which case navigation is done with function calls, as the . is a valid character in XML names. However, it is not recommended to use this unless you have XML to deal with as well.

    jnlib:values($content("books")("reader"))("book")("name")