Mastering JsonPath Filters: From Existence Checks to Array Length Queries
This tutorial demonstrates how to use JsonPath for advanced JSON filtering, covering property existence checks, string and numeric value comparisons, property-to-property comparisons, and array length evaluation, with clear Java code examples and explanations of common pitfalls.
JSON Data
A sample JSON document is defined, containing a store with an array of books and a bicycle, plus additional fields such as "expensive" and an integer array "ss".
JSONObject json = JSON.parseObject("{\"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}},\"expensive\":10,\"ss\":[32,32,4,23]}");Checking Property Existence
The JsonPath expression $..book[?(@.isbn)] selects all book objects that contain an isbn field.
Object read = JsonPath.read(json, "$..book[?(@.isbn)]");
output(JSONArray.parseArray(read.toString()));The console output shows the two books that have an isbn attribute.
Value Comparison
String comparison example: $..book[?(@.isbn == '0-395-19395-8')] returns the book with that exact ISBN.
Numeric comparison example: $..book[?(@.price > 20)] returns books whose price exceeds 20.
Object read = JsonPath.read(json, "$..book[?(@.price > 20)]");
output(JSONArray.parseArray(read.toString()));Comparing Property to Property
A nested JsonPath expression can compare a property against another property in the same document, e.g., $..book[?(@.price > $['expensive'])] selects books whose price is greater than the top‑level expensive value.
Object read = JsonPath.read(json, "$..book[?(@.price > $['expensive'])]");
output(JSONArray.parseArray(read.toString()));Array Length Evaluation
The length() function returns the size of an array: $..book.length() yields the number of books (4). A noted pitfall is that applying length() after a filter changes its semantics, returning the length of the filtered result as a numeric array rather than a single integer.
Object read = JsonPath.read(json, "$..book.length()");
output(read);Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
