Search code examples
javajsonpathjson-path-expression

JsonPath array length() returns number of keys instead of elements


I have the following array:

"books" : [ {
  "title" : "History",
  "id":1

}, {
  "title" : "The Robotics",
  "id":2

}, {
  "title" : "The World",
   "id":3
} ]

and my JsonPath notation is this: $.books[?(@.title == 'History')].length() . I'm expecting it to return 1 (because it matches a single book), but it returns 2, which is a number of keys in the first object(that got matched). How can I force/change it to return the number of elements, not keys in the object?

Im using this library for java.


Solution

  • The problem lies in the dot (.). You have only one but you need two. This works:

    $..books[?(@.title == 'History')].length()