Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions min(), max() or sum() with jsonpath

Tags:

java

jsonpath

According to JsonPath on GitHub it shall be possible to access max(), min() or the sum() of an array but I dont know how. With this exampledata:

{
  "store": {
    "book": [
      {
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      {
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

I would expect it to work like

$..book.length

so im trying

$..price.sum

but that didn't do the job.

Can someone help me?

like image 838
smaica Avatar asked Mar 05 '23 06:03

smaica


1 Answers

From the docs:

Functions can be invoked at the tail end of a path - the input to a function is the output of the path expression

Given this statement, you might expect the example JSON you supplied above to work with an expression such as $.store..price.max() but this expression does not work, instead it throws an error:

Aggregation function attempted to calculate value using empty array

You can read more about that in this JsonPath issue on GitHub.

Meanwhile, here's an example which does work.

Given the following JSON:

{
  "price": [
      1.0,
      2.0
  ]
}

The JsonPath functions work as follows:

  • $..price.min() returns [1.0]
  • $..price.max() returns [2.0]
  • $..price.sum() returns [3.0]

The above have been verified using the online evaluator.

like image 137
glytching Avatar answered Mar 27 '23 20:03

glytching