0

This seems very much possible, but I can't get it to work. Could be my JSON or my jsonpath selector. Not sure.

Here's the simple JSON showing a book inventory with the cost of 10 and 20 copies, along with which ones are On Sale:

{
    "Books": {
        "1": {
            "Title": "Title of the 1st book",
            "Cost": {
                "10": 19.95,
                "20": 29.95
            },
            "OnSale": 0
        },
        "2": {
            "Title": "Title of the 2nd book",
            "Cost": {
                "10": 9.95,
                "20": 39.95
            },
            "OnSale": 1
        },
        "3": {
            "Title": "Title of the 3rd book",
            "Cost": {
                "10": 5.95,
                "20": 49.95
            },
            "OnSale": 0
        }
    },
    "ChosenQuantity": "10" 
}

Using the stefan.goessner jsonpath library, I want the cost of 10 books that are On Sale with the following jsonpath selector:

$.Books[?(@.OnSale==1)].Cost[?($.ChosenQuantity)]

I can't hard code any of the key values into the jsonpath selector.

With the above jsonpath, what I'm expecting:

[
    9.95
]

Instead, I'm getting the following:

[
    9.95,
    39.95
]

To test, I've been using https://jsonpath.herokuapp.com/ with the Goessner implementation.

Is the problem in the JSON, the jsonpath selector filters, or both?

arzoum
  • 49
  • 4

1 Answers1

0

Try using:

$.Books[?(@.OnSale==1)].Cost.10

or (depending on where you test it):

$.Books..[?(@.OnSale==1)].Cost.10

It should get you the right value.

Jack Fleeting
  • 24,385
  • 6
  • 23
  • 45
  • Unfortunately, that doesn't work. You can test it with https://jsonpath.herokuapp.com/ – arzoum Jun 28 '20 at 23:23
  • 1
    @arzoum Well, that's the problem with json - it depends where you check (which is why xpath is indeed better....); it works on that site under the Goessner tab. Also works here: https://jsonpath.com/. – Jack Fleeting Jun 28 '20 at 23:27
  • Hard coding the "10" into the selector does work. What I'm looking for is the correct syntax for the filter that uses the value of `$.ChosenQuantity` as the key to pull the value for `Cost`. – arzoum Jun 28 '20 at 23:55
  • Is it supposed to works ? Installed Ruby jsonpath: `jsonpath '$.Books[?(@.OnSale==1)].Cost.10' file`. I get `[]` – Gilles Quénot Jun 29 '20 at 00:56
  • @GillesQuenot There are several implementations of jsonpath. The one I'm using is called the [Goessner implementation](https://goessner.net/articles/JsonPath/) – arzoum Jun 29 '20 at 13:15
  • @arzoum I'm afraid I couldn't come up with a way to replace the hardcoding of "10" with a value of `$.ChosenQuantity`; I suspect it may be impossible with jsonpath, but will be happy to be corrected. – Jack Fleeting Jun 30 '20 at 15:55