0
# Filtering and Predicates
1
2
Advanced filtering capabilities for creating complex queries with predicates, criteria builders, and custom filters. JsonPath supports sophisticated filtering using expressions within bracket notation.
3
4
## Capabilities
5
6
### Filter Creation and Operations
7
8
Core Filter class providing factory methods and logical operations for combining filters.
9
10
```java { .api }
11
/**
12
* Abstract base class for filtering JSON elements
13
*/
14
public abstract class Filter implements Predicate {
15
/**
16
* Creates a new Filter based on a single predicate
17
* @param predicate Predicate to wrap in filter
18
* @return Filter instance
19
*/
20
public static Filter filter(Predicate predicate);
21
22
/**
23
* Creates a new Filter based on multiple predicates (all must be true)
24
* @param predicates Collection of predicates that all must evaluate to true
25
* @return Filter instance combining all predicates with AND logic
26
*/
27
public static Filter filter(Collection<Predicate> predicates);
28
29
/**
30
* Parses a filter expression from string
31
* @param filter Filter string to parse (should match [?(<expression>)] format)
32
* @return Parsed Filter instance
33
* @throws InvalidCriteriaException If filter string is invalid
34
*/
35
public static Filter parse(String filter);
36
37
/**
38
* Applies this filter to the given context
39
* @param ctx Predicate context containing current item and root document
40
* @return true if filter matches, false otherwise
41
*/
42
public abstract boolean apply(PredicateContext ctx);
43
44
/**
45
* Combines this filter with another using OR logic
46
* @param other Predicate to combine with OR
47
* @return New Filter representing (this OR other)
48
*/
49
public Filter or(Predicate other);
50
51
/**
52
* Combines this filter with another using AND logic
53
* @param other Predicate to combine with AND
54
* @return New Filter representing (this AND other)
55
*/
56
public Filter and(Predicate other);
57
}
58
```
59
60
**Usage Examples:**
61
62
```java
63
import com.jayway.jsonpath.Filter;
64
import com.jayway.jsonpath.Criteria;
65
import com.jayway.jsonpath.JsonPath;
66
import java.util.List;
67
68
String json = "{ \"books\": [" +
69
"{ \"category\": \"fiction\", \"author\": \"Smith\", \"price\": 8.95 }," +
70
"{ \"category\": \"fiction\", \"author\": \"Johnson\", \"price\": 12.99 }," +
71
"{ \"category\": \"reference\", \"author\": \"Brown\", \"price\": 15.50 }" +
72
"] }";
73
74
// Create filter using Criteria
75
Filter priceFilter = Filter.filter(Criteria.where("price").lt(10));
76
List<Object> cheapBooks = JsonPath.read(json, "$.books[?]", priceFilter);
77
78
// Parse filter from string
79
Filter categoryFilter = Filter.parse("[?(@.category == 'fiction')]");
80
List<Object> fictionBooks = JsonPath.read(json, "$.books[?]", categoryFilter);
81
82
// Combine filters with logical operations
83
Filter combinedFilter = priceFilter.and(categoryFilter);
84
List<Object> cheapFiction = JsonPath.read(json, "$.books[?]", combinedFilter);
85
86
// Using OR logic
87
Filter expensiveFilter = Filter.filter(Criteria.where("price").gt(15));
88
Filter extremePriceFilter = priceFilter.or(expensiveFilter);
89
List<Object> extremelyPricedBooks = JsonPath.read(json, "$.books[?]", extremePriceFilter);
90
```
91
92
### Predicate Interface
93
94
Core predicate interface and context for filter evaluation.
95
96
```java { .api }
97
/**
98
* Interface for predicate functions used in filtering
99
*/
100
public interface Predicate {
101
/**
102
* Applies this predicate to the given context
103
* @param ctx Context containing current item and evaluation state
104
* @return true if predicate matches, false otherwise
105
*/
106
boolean apply(PredicateContext ctx);
107
108
/**
109
* Context interface providing access to current item and root document
110
*/
111
public interface PredicateContext {
112
/**
113
* Returns the current item being evaluated by this predicate
114
* @return Current document/item
115
*/
116
Object item();
117
118
/**
119
* Returns the current item mapped to the specified class
120
* @param clazz Target class for mapping
121
* @return Current item mapped to specified type
122
* @throws MappingException If mapping fails
123
*/
124
<T> T item(Class<T> clazz) throws MappingException;
125
126
/**
127
* Returns the root document (complete JSON being queried)
128
* @return Root document
129
*/
130
Object root();
131
132
/**
133
* Returns configuration used for evaluation
134
* @return Configuration instance
135
*/
136
Configuration configuration();
137
}
138
}
139
```
140
141
**Usage Examples:**
142
143
```java
144
import com.jayway.jsonpath.Predicate;
145
import com.jayway.jsonpath.JsonPath;
146
import java.util.Map;
147
148
// Custom predicate implementation
149
Predicate customPredicate = new Predicate() {
150
public boolean apply(PredicateContext ctx) {
151
Object item = ctx.item();
152
if (item instanceof Map) {
153
Map<String, Object> book = (Map<String, Object>) item;
154
String author = (String) book.get("author");
155
return author != null && author.length() > 5;
156
}
157
return false;
158
}
159
};
160
161
// Use custom predicate
162
List<Object> longAuthorNameBooks = JsonPath.read(json, "$.books[?]", customPredicate);
163
164
// Access different context elements
165
Predicate contextAwarePredicate = new Predicate() {
166
public boolean apply(PredicateContext ctx) {
167
// Current item being evaluated
168
Map<String, Object> currentBook = ctx.item(Map.class);
169
170
// Root document for comparison
171
Map<String, Object> root = (Map<String, Object>) ctx.root();
172
173
// Use configuration if needed
174
Configuration config = ctx.configuration();
175
176
return ((Number) currentBook.get("price")).doubleValue() > 10.0;
177
}
178
};
179
```
180
181
### Criteria Builder
182
183
Fluent API for building complex filter criteria with various comparison operations.
184
185
```java { .api }
186
/**
187
* Builder class for creating filter predicates with fluent API
188
*/
189
public class Criteria implements Predicate {
190
/**
191
* Creates a new Criteria for the specified field
192
* @param key Field name to create criteria for
193
* @return Criteria instance for chaining operations
194
*/
195
public static Criteria where(String key);
196
197
/**
198
* Adds an AND condition for another field
199
* @param key Field name for additional criteria
200
* @return Criteria instance for chaining
201
*/
202
public Criteria and(String key);
203
204
/**
205
* Applies this criteria as a predicate
206
* @param ctx Predicate context
207
* @return true if criteria matches
208
*/
209
public boolean apply(PredicateContext ctx);
210
}
211
```
212
213
### Comparison Operations
214
215
Various comparison operators available in the Criteria builder.
216
217
```java { .api }
218
/**
219
* Equality operations
220
*/
221
public Criteria is(Object o); // Alias for eq()
222
public Criteria eq(Object o); // Equal to
223
public Criteria ne(Object o); // Not equal to
224
225
/**
226
* Numeric comparison operations
227
*/
228
public Criteria lt(Object o); // Less than
229
public Criteria lte(Object o); // Less than or equal
230
public Criteria gt(Object o); // Greater than
231
public Criteria gte(Object o); // Greater than or equal
232
233
/**
234
* String operations
235
*/
236
public Criteria regex(Pattern pattern); // Regular expression match
237
238
/**
239
* Collection operations
240
*/
241
public Criteria in(Object... o); // Value in array
242
public Criteria in(Collection<?> c); // Value in collection
243
public Criteria nin(Object... o); // Value not in array
244
public Criteria nin(Collection<?> c); // Value not in collection
245
public Criteria contains(Object o); // Contains value
246
public Criteria all(Object... o); // Contains all values
247
public Criteria all(Collection<?> c); // Contains all values
248
public Criteria subsetof(Object... o); // Is subset of
249
public Criteria subsetof(Collection<?> c); // Is subset of collection
250
public Criteria anyof(Object... o); // Has any of values
251
public Criteria anyof(Collection<?> c); // Has any of collection values
252
public Criteria noneof(Object... o); // Has none of values
253
public Criteria noneof(Collection<?> c); // Has none of collection values
254
255
/**
256
* Type and size operations
257
*/
258
public Criteria type(Class<?> clazz); // Value is of specified type
259
public Criteria size(int size); // Array/string has specified size
260
public Criteria exists(boolean shouldExist); // Field exists/doesn't exist
261
public Criteria empty(boolean empty); // Array/string is empty/not empty
262
263
/**
264
* Advanced operations
265
*/
266
public Criteria matches(Predicate p); // Matches custom predicate
267
```
268
269
**Usage Examples:**
270
271
```java
272
import com.jayway.jsonpath.Criteria;
273
import com.jayway.jsonpath.Filter;
274
import com.jayway.jsonpath.JsonPath;
275
import java.util.Arrays;
276
import java.util.regex.Pattern;
277
278
String json = "{ \"books\": [" +
279
"{ \"category\": \"fiction\", \"author\": \"Herman Melville\", \"price\": 8.95, \"isbn\": \"123456789\", \"tags\": [\"classic\", \"literature\"] }," +
280
"{ \"category\": \"fiction\", \"author\": \"J.K. Rowling\", \"price\": 12.99, \"isbn\": \"987654321\", \"tags\": [\"fantasy\", \"young-adult\"] }," +
281
"{ \"category\": \"reference\", \"author\": \"Oxford Press\", \"price\": 15.50, \"tags\": [\"reference\", \"dictionary\"] }" +
282
"] }";
283
284
// Basic equality
285
Filter fictionFilter = Filter.filter(Criteria.where("category").eq("fiction"));
286
287
// Numeric comparisons
288
Filter cheapFilter = Filter.filter(Criteria.where("price").lt(10));
289
Filter expensiveFilter = Filter.filter(Criteria.where("price").gte(15));
290
291
// String operations with regex
292
Pattern authorPattern = Pattern.compile(".*Melville.*");
293
Filter authorFilter = Filter.filter(Criteria.where("author").regex(authorPattern));
294
295
// Collection operations
296
Filter isbnInList = Filter.filter(Criteria.where("isbn").in("123456789", "555666777"));
297
Filter hasFantasyTag = Filter.filter(Criteria.where("tags").contains("fantasy"));
298
Filter hasAllRequiredTags = Filter.filter(Criteria.where("tags").all("fiction", "literature"));
299
300
// Type and existence checks
301
Filter hasAuthor = Filter.filter(Criteria.where("author").exists(true));
302
Filter priceIsNumber = Filter.filter(Criteria.where("price").type(Number.class));
303
Filter shortIsbn = Filter.filter(Criteria.where("isbn").size(9));
304
305
// Complex criteria with AND conditions
306
Filter complexFilter = Filter.filter(
307
Criteria.where("category").eq("fiction")
308
.and("price").lt(15)
309
.and("tags").contains("classic")
310
);
311
312
// Using filters in queries
313
List<Object> fictionBooks = JsonPath.read(json, "$.books[?]", fictionFilter);
314
List<Object> cheapBooks = JsonPath.read(json, "$.books[?]", cheapFilter);
315
List<Object> complexResults = JsonPath.read(json, "$.books[?]", complexFilter);
316
317
// Empty/non-empty checks
318
String jsonWithEmptyArrays = "{ \"items\": [{ \"tags\": [] }, { \"tags\": [\"tag1\"] }] }";
319
Filter hasEmptyTags = Filter.filter(Criteria.where("tags").empty(true));
320
Filter hasNonEmptyTags = Filter.filter(Criteria.where("tags").empty(false));
321
```
322
323
### Inline Filter Expressions
324
325
JsonPath also supports inline filter expressions directly in the path string.
326
327
**Filter Expression Syntax:**
328
329
```java
330
// Basic comparisons
331
"$.books[?(@.price < 10)]" // Price less than 10
332
"$.books[?(@.category == 'fiction')]" // Category equals fiction
333
"$.books[?(@.author != 'Unknown')]" // Author not equal to Unknown
334
335
// Regular expressions
336
"$.books[?(@.author =~ /.*Smith.*/)]" // Author matches regex pattern
337
338
// Multiple conditions
339
"$.books[?(@.price < 10 && @.category == 'fiction')]" // AND condition
340
"$.books[?(@.price < 5 || @.price > 20)]" // OR condition
341
342
// Array operations
343
"$.books[?(@.tags[*] in ['fiction', 'drama'])]" // Any tag is in list
344
"$.books[?(@.tags.length() > 2)]" // More than 2 tags
345
346
// Existence checks
347
"$.books[?(@.isbn)]" // Has isbn field
348
"$.books[?(!@.discount)]" // Doesn't have discount field
349
350
// Root reference
351
"$.books[?(@.price < $.averagePrice)]" // Price less than root averagePrice
352
```
353
354
**Usage Examples:**
355
356
```java
357
import com.jayway.jsonpath.JsonPath;
358
import java.util.List;
359
360
// Direct inline filtering
361
List<Object> cheapBooks = JsonPath.read(json, "$.books[?(@.price < 10)]");
362
List<Object> fictionBooks = JsonPath.read(json, "$.books[?(@.category == 'fiction')]");
363
List<Object> authorBooks = JsonPath.read(json, "$.books[?(@.author =~ /.*Melville.*/)]");
364
365
// Complex inline expressions
366
List<Object> complexQuery = JsonPath.read(json,
367
"$.books[?(@.price < 15 && @.category == 'fiction' && @.tags[*] in ['classic'])]");
368
369
// Using functions in filters
370
List<Object> multipleTags = JsonPath.read(json, "$.books[?(@.tags.length() > 1)]");
371
372
// Existence checks
373
List<Object> hasIsbn = JsonPath.read(json, "$.books[?(@.isbn)]");
374
List<Object> noDiscount = JsonPath.read(json, "$.books[?(!@.discount)]");
375
```