Search code examples
jsonxqueryflworjsoniq

How to use JSONiq for JSON


The question is to write a JSONiq FLWOR expression that can display the name of the products which their price are at least 3.

I have tried the answers provided on How to run JSONiq from JSON with try.zorba.io but that's not the answers that i expect. Beside that, I also tried a lot of JSON FLWOR expression but still getting errors in try.zobia.io. This is my JSON file.

{
    "supermarket": {
        "visit": [ {
            "_type": "bought", 
            "date": "March 8th, 2019",
            "product": [ {
                    "name": "Kit Kat",
                    "amount": 3,
                    "cost": 3.5
                    },
                {
                    "name": "Coca Cola",
                    "amount": 2,
                    "cost": 3
                    },
                {
                    "name": "Apple",
                    "amount": "Some",
                    "cost": 5.9
                    }
                ]
            },  
            {
            "_type": "planning", 
            "product": [{
                    "name": "Pen",
                    "amount": 2
                    },
                {
                    "name": "Paper",
                    "amount": "One ream"
                    }
                ]
            }
        ]
    }
}

This is my current JSONiq expression.

jsoniq version "1.0";
let $a := { (: my JSON file :) }    
for $x in $a.supermarket.visit
let $y = $x.product()
where $y.price >= "3.0"
return $y.name

The final output should be Kit Kat, Coca Cola and Apple. I would appreciate some helps for my JSON file or JSONiq.


Solution

  • visit also is an array, so you need the parenthesis to get to the individual visits in the for. This

    jsoniq version "1.0";
    let $data := { (: my JSON file :) }
    for $visit in $data.supermarket.visit()
    for $product in $visit.product()
    where $product.cost ge 3
    return $product.name
    

    would return

    Kit Kat Coca Cola Apple
    

    Since the above produces a sequence, you can use it anywhere where sequences are allowed.

    let $data := { (: my JSON file :) }
    return string-join(
      for $visit in $data.supermarket.visit()
      for $product in $visit.product()
      where $product.cost ge 3
      return $product.name
    , ", ")
    

    Result:

    Kit Kat, Coca Cola, Apple
    

    Of course this would work as well:

    for $product in $data.supermarket.visit().product()
    where $product.cost ge 3
    return $product.name