0
# Core Path Operations
1
2
Primary JsonPath functionality for reading JSON documents using path expressions. This covers both static utility methods and compiled path instances for efficient reuse.
3
4
## Capabilities
5
6
### Static Read Operations
7
8
Convenience methods for one-time path evaluations on various input sources.
9
10
```java { .api }
11
/**
12
* Reads from a parsed JSON object using a JsonPath expression
13
* @param json Parsed JSON object (Map, List, or other JSON structure)
14
* @param jsonPath JsonPath expression string
15
* @param filters Optional predicates for filtering
16
* @return Result matching the path expression
17
*/
18
public static <T> T read(Object json, String jsonPath, Predicate... filters);
19
20
/**
21
* Reads from a JSON string using a JsonPath expression
22
* @param json JSON string to parse and query
23
* @param jsonPath JsonPath expression string
24
* @param filters Optional predicates for filtering
25
* @return Result matching the path expression
26
*/
27
public static <T> T read(String json, String jsonPath, Predicate... filters);
28
29
/**
30
* Reads from a JSON file using a JsonPath expression
31
* @param jsonFile File containing JSON data
32
* @param jsonPath JsonPath expression string
33
* @param filters Optional predicates for filtering
34
* @return Result matching the path expression
35
* @throws IOException If file cannot be read
36
*/
37
public static <T> T read(File jsonFile, String jsonPath, Predicate... filters) throws IOException;
38
39
/**
40
* Reads from a JSON input stream using a JsonPath expression
41
* @param jsonInputStream Input stream containing JSON data
42
* @param jsonPath JsonPath expression string
43
* @param filters Optional predicates for filtering
44
* @return Result matching the path expression
45
* @throws IOException If stream cannot be read
46
*/
47
public static <T> T read(InputStream jsonInputStream, String jsonPath, Predicate... filters) throws IOException;
48
```
49
50
**Usage Examples:**
51
52
```java
53
import com.jayway.jsonpath.JsonPath;
54
import java.util.List;
55
56
String json = "{ \"users\": [{ \"name\": \"Alice\", \"age\": 30 }, { \"name\": \"Bob\", \"age\": 25 }] }";
57
58
// Read single value
59
String firstName = JsonPath.read(json, "$.users[0].name");
60
// Result: "Alice"
61
62
// Read multiple values
63
List<String> names = JsonPath.read(json, "$.users[*].name");
64
// Result: ["Alice", "Bob"]
65
66
// Read from file
67
List<Integer> ages = JsonPath.read(new File("users.json"), "$.users[*].age");
68
69
// With filtering
70
List<String> olderUsers = JsonPath.read(json, "$.users[?(@.age > 25)].name");
71
// Result: ["Alice"]
72
```
73
74
### Path Compilation
75
76
Compile JsonPath expressions for efficient reuse when the same path will be evaluated multiple times.
77
78
```java { .api }
79
/**
80
* Compiles a JsonPath expression for reuse
81
* @param jsonPath JsonPath expression string to compile
82
* @param filters Optional predicates to include in compiled path
83
* @return Compiled JsonPath instance
84
* @throws InvalidPathException If the path expression is invalid
85
*/
86
public static JsonPath compile(String jsonPath, Predicate... filters);
87
88
/**
89
* Checks if a path expression is definite (points to single item)
90
* @param path JsonPath expression to check
91
* @return true if path is definite, false otherwise
92
*/
93
public static boolean isPathDefinite(String path);
94
```
95
96
**Usage Examples:**
97
98
```java
99
import com.jayway.jsonpath.JsonPath;
100
101
// Compile path for reuse
102
JsonPath userNamesPath = JsonPath.compile("$.users[*].name");
103
104
// Use compiled path multiple times
105
List<String> names1 = userNamesPath.read(json1);
106
List<String> names2 = userNamesPath.read(json2);
107
List<String> names3 = userNamesPath.read(jsonObject);
108
109
// Check if path is definite
110
boolean isDefinite = JsonPath.isPathDefinite("$.users[0].name"); // true
111
boolean isIndefinite = JsonPath.isPathDefinite("$.users[*].name"); // false
112
```
113
114
### Compiled Path Instance Methods
115
116
Methods available on compiled JsonPath instances for reading from various sources.
117
118
```java { .api }
119
/**
120
* Returns the string representation of this JsonPath
121
* @return path as String
122
*/
123
public String getPath();
124
125
/**
126
* Checks if path points to a single item or potentially multiple items
127
* @return true if path is definite (points to single item)
128
*/
129
public boolean isDefinite();
130
131
/**
132
* Applies this JsonPath to a parsed JSON object
133
* @param jsonObject Container object (Map, List, etc.)
134
* @return Objects matched by the path
135
*/
136
public <T> T read(Object jsonObject);
137
138
/**
139
* Applies this JsonPath to a parsed JSON object with configuration
140
* @param jsonObject Container object
141
* @param configuration Configuration to use
142
* @return Objects matched by the path
143
*/
144
public <T> T read(Object jsonObject, Configuration configuration);
145
146
/**
147
* Applies this JsonPath to a JSON string
148
* @param json JSON string to parse and query
149
* @return Objects matched by the path
150
*/
151
public <T> T read(String json);
152
153
/**
154
* Applies this JsonPath to a JSON string with configuration
155
* @param json JSON string to parse and query
156
* @param configuration Configuration to use
157
* @return Objects matched by the path
158
*/
159
public <T> T read(String json, Configuration configuration);
160
161
/**
162
* Applies this JsonPath to a JSON file
163
* @param jsonFile File containing JSON data
164
* @return Objects matched by the path
165
* @throws IOException If file cannot be read
166
*/
167
public <T> T read(File jsonFile) throws IOException;
168
169
/**
170
* Applies this JsonPath to a JSON file with configuration
171
* @param jsonFile File containing JSON data
172
* @param configuration Configuration to use
173
* @return Objects matched by the path
174
* @throws IOException If file cannot be read
175
*/
176
public <T> T read(File jsonFile, Configuration configuration) throws IOException;
177
178
/**
179
* Applies this JsonPath to a JSON input stream
180
* @param jsonInputStream Input stream containing JSON data
181
* @return Objects matched by the path
182
* @throws IOException If stream cannot be read
183
*/
184
public <T> T read(InputStream jsonInputStream) throws IOException;
185
186
/**
187
* Applies this JsonPath to a JSON input stream with configuration
188
* @param jsonInputStream Input stream containing JSON data
189
* @param configuration Configuration to use
190
* @return Objects matched by the path
191
* @throws IOException If stream cannot be read
192
*/
193
public <T> T read(InputStream jsonInputStream, Configuration configuration) throws IOException;
194
195
/**
196
* Applies this JsonPath to a JSON input stream with explicit charset
197
* @param jsonInputStream Input stream containing JSON data
198
* @param charset Character encoding of the stream
199
* @param configuration Configuration to use
200
* @return Objects matched by the path
201
* @throws IOException If stream cannot be read
202
*/
203
public <T> T read(InputStream jsonInputStream, String charset, Configuration configuration) throws IOException;
204
```
205
206
### Compiled Path Write Operations
207
208
Methods for modifying JSON documents using compiled JsonPath instances.
209
210
```java { .api }
211
/**
212
* Sets the value at the path location in the JSON object
213
* @param jsonObject JSON object to modify
214
* @param newVal New value to set at path location
215
* @param configuration Configuration to use
216
* @return Modified JSON object or path list if AS_PATH_LIST option is set
217
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
218
*/
219
public <T> T set(Object jsonObject, Object newVal, Configuration configuration);
220
221
/**
222
* Transforms values at the path location using a mapping function
223
* @param jsonObject JSON object to modify
224
* @param mapFunction Function to transform current values
225
* @param configuration Configuration to use
226
* @return Modified JSON object or path list if AS_PATH_LIST option is set
227
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
228
*/
229
public <T> T map(Object jsonObject, MapFunction mapFunction, Configuration configuration);
230
231
/**
232
* Deletes the elements at the path location
233
* @param jsonObject JSON object to modify
234
* @param configuration Configuration to use
235
* @return Modified JSON object or path list if AS_PATH_LIST option is set
236
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
237
*/
238
public <T> T delete(Object jsonObject, Configuration configuration);
239
240
/**
241
* Adds a value to arrays at the path location
242
* @param jsonObject JSON object to modify
243
* @param value Value to add to arrays
244
* @param configuration Configuration to use
245
* @return Modified JSON object or path list if AS_PATH_LIST option is set
246
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
247
* @throws InvalidModificationException If path doesn't point to an array
248
*/
249
public <T> T add(Object jsonObject, Object value, Configuration configuration);
250
251
/**
252
* Adds or updates a key-value pair in objects at the path location
253
* @param jsonObject JSON object to modify
254
* @param key Key to add or update
255
* @param value Value for the key
256
* @param configuration Configuration to use
257
* @return Modified JSON object or path list if AS_PATH_LIST option is set
258
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
259
* @throws InvalidModificationException If path doesn't point to an object
260
*/
261
public <T> T put(Object jsonObject, String key, Object value, Configuration configuration);
262
263
/**
264
* Renames a key in objects at the path location
265
* @param jsonObject JSON object to modify
266
* @param oldKeyName Current key name to rename
267
* @param newKeyName New key name
268
* @param configuration Configuration to use
269
* @return Modified JSON object or path list if AS_PATH_LIST option is set
270
* @throws PathNotFoundException If path is not found and SUPPRESS_EXCEPTIONS is not set
271
* @throws InvalidModificationException If path doesn't point to an object or key doesn't exist
272
*/
273
public <T> T renameKey(Object jsonObject, String oldKeyName, String newKeyName, Configuration configuration);
274
```
275
276
**Usage Examples:**
277
278
```java
279
import com.jayway.jsonpath.JsonPath;
280
import com.jayway.jsonpath.Configuration;
281
import com.jayway.jsonpath.MapFunction;
282
283
String json = "{ \"users\": [{ \"name\": \"Alice\", \"age\": 30 }, { \"name\": \"Bob\", \"age\": 25 }] }";
284
Configuration config = Configuration.defaultConfiguration();
285
286
// Compile path for write operations
287
JsonPath agePath = JsonPath.compile("$.users[0].age");
288
JsonPath usersPath = JsonPath.compile("$.users");
289
290
// Set value
291
Object result = agePath.set(JsonPath.parse(json).json(), 31, config);
292
293
// Transform values using mapping function
294
MapFunction incrementAge = (currentValue, configuration) -> {
295
if (currentValue instanceof Integer) {
296
return ((Integer) currentValue) + 1;
297
}
298
return currentValue;
299
};
300
Object transformed = agePath.map(JsonPath.parse(json).json(), incrementAge, config);
301
302
// Add new user to array
303
Object withNewUser = usersPath.add(JsonPath.parse(json).json(),
304
Map.of("name", "Charlie", "age", 28), config);
305
306
// Add property to first user
307
JsonPath firstUserPath = JsonPath.compile("$.users[0]");
308
Object withEmail = firstUserPath.put(JsonPath.parse(json).json(), "email", "alice@example.com", config);
309
310
// Rename property
311
Object renamed = firstUserPath.renameKey(JsonPath.parse(json).json(), "age", "yearsOld", config);
312
313
// Delete user
314
JsonPath secondUserPath = JsonPath.compile("$.users[1]");
315
Object afterDelete = secondUserPath.delete(JsonPath.parse(json).json(), config);
316
```
317
318
### Parse Context Creation
319
320
Factory methods for creating parse contexts with different configurations.
321
322
```java { .api }
323
/**
324
* Creates a ParseContext with the specified configuration
325
* @param configuration Configuration to use for parsing
326
* @return ParseContext instance
327
*/
328
public static ParseContext using(Configuration configuration);
329
330
/**
331
* Creates a ParseContext with the specified JSON provider (deprecated)
332
* @param provider JsonProvider to use for parsing
333
* @return ParseContext instance
334
*/
335
@Deprecated
336
public static ParseContext using(JsonProvider provider);
337
```
338
339
**Usage Examples:**
340
341
```java
342
import com.jayway.jsonpath.JsonPath;
343
import com.jayway.jsonpath.Configuration;
344
import com.jayway.jsonpath.Option;
345
import com.jayway.jsonpath.ParseContext;
346
347
// Create parse context with custom configuration
348
Configuration config = Configuration.builder()
349
.options(Option.SUPPRESS_EXCEPTIONS, Option.ALWAYS_RETURN_LIST)
350
.build();
351
352
ParseContext parseContext = JsonPath.using(config);
353
DocumentContext doc = parseContext.parse(jsonString);
354
```
355
356
## Path Expression Syntax
357
358
JsonPath expressions use a specific syntax for navigating JSON structures:
359
360
- `$` - Root element
361
- `.property` - Child property (dot notation)
362
- `['property']` - Child property (bracket notation)
363
- `[index]` - Array element by index
364
- `[start:end]` - Array slice
365
- `[*]` - All array elements or object properties
366
- `..property` - Recursive descent (deep scan)
367
- `[?(@.property == 'value')]` - Filter expression
368
- `[(@.length-1)]` - Expression in brackets
369
370
**Common Path Examples:**
371
372
```java
373
// Simple property access
374
"$.store.name" // dot notation
375
"$['store']['name']" // bracket notation
376
377
// Array access
378
"$.books[0]" // first book
379
"$.books[-1]" // last book
380
"$.books[1:3]" // books at index 1 and 2
381
"$.books[*]" // all books
382
383
// Wildcards and recursive
384
"$.store.*" // all properties of store
385
"$..price" // all price properties at any level
386
387
// Filtering
388
"$.books[?(@.price < 10)]" // books cheaper than 10
389
"$.books[?(@.category == 'fiction')]" // fiction books
390
"$.books[?(@.author =~ /.*Smith/)]" // books by authors named Smith
391
```