0

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.

sparrow2
  • 147
  • 1
  • 11

1 Answers1

1

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

$..books[?(@.title == 'History')].length()
TimonNetherlands
  • 1,033
  • 1
  • 6
  • 6
  • Thanks @Timon. The thing is that I don't write the java code, Im using library that does this for me. The strange thing is that when I write `$.books.length()` it returns 3 as expected , but if I have filter and then length() , it counts keys in object – sparrow2 Mar 02 '21 at 11:22
  • I've updated the answer with a working solution. – TimonNetherlands Mar 02 '21 at 11:44
  • It still gives me 2, but I guess this is due to the library Im using. Thanks anyway – sparrow2 Mar 02 '21 at 12:09
  • Btw, how can I check if array is empty, I tries empty(), but does not work – sparrow2 Mar 02 '21 at 12:10
  • It seems my answer doesn't help. This code always returns length 1. I'll remove this answer in a few minutes. – TimonNetherlands Mar 02 '21 at 13:10