0
# Document Context Operations
1
2
Comprehensive read and write operations on parsed JSON documents. DocumentContext provides both reading capabilities and document modification features, combining ReadContext and WriteContext interfaces.
3
4
## Capabilities
5
6
### Document Parsing
7
8
Factory methods for creating DocumentContext instances from various JSON sources.
9
10
```java { .api }
11
/**
12
* Parses JSON object using default configuration
13
* @param json Parsed JSON object (Map, List, etc.)
14
* @return DocumentContext for path operations
15
*/
16
public static DocumentContext parse(Object json);
17
18
/**
19
* Parses JSON string using default configuration
20
* @param json JSON string to parse
21
* @return DocumentContext for path operations
22
*/
23
public static DocumentContext parse(String json);
24
25
/**
26
* Parses JSON file using default configuration
27
* @param json File containing JSON data
28
* @return DocumentContext for path operations
29
* @throws IOException If file cannot be read
30
*/
31
public static DocumentContext parse(File json) throws IOException;
32
33
/**
34
* Parses JSON input stream using default configuration
35
* @param json Input stream containing JSON data
36
* @return DocumentContext for path operations
37
*/
38
public static DocumentContext parse(InputStream json);
39
40
/**
41
* Parses JSON with specific configuration
42
* @param json JSON source (Object, String, File, or InputStream)
43
* @param configuration Configuration to use for parsing
44
* @return DocumentContext for path operations
45
*/
46
public static DocumentContext parse(Object json, Configuration configuration);
47
public static DocumentContext parse(String json, Configuration configuration);
48
public static DocumentContext parse(File json, Configuration configuration) throws IOException;
49
public static DocumentContext parse(InputStream json, Configuration configuration);
50
```
51
52
**Usage Examples:**
53
54
```java
55
import com.jayway.jsonpath.JsonPath;
56
import com.jayway.jsonpath.DocumentContext;
57
import com.jayway.jsonpath.Configuration;
58
import com.jayway.jsonpath.Option;
59
60
String json = "{ \"users\": [{ \"name\": \"Alice\", \"age\": 30 }] }";
61
62
// Parse with default configuration
63
DocumentContext context = JsonPath.parse(json);
64
65
// Parse with custom configuration
66
Configuration config = Configuration.builder()
67
.options(Option.SUPPRESS_EXCEPTIONS)
68
.build();
69
DocumentContext configuredContext = JsonPath.parse(json, config);
70
71
// Parse from file
72
DocumentContext fileContext = JsonPath.parse(new File("data.json"));
73
```
74
75
### Reading Operations
76
77
Reading data from the parsed JSON document using path expressions.
78
79
```java { .api }
80
/**
81
* Returns the configuration used for reading
82
* @return Immutable configuration
83
*/
84
public Configuration configuration();
85
86
/**
87
* Returns the JSON model this context operates on
88
* @return JSON model as object
89
*/
90
public <T> T json();
91
92
/**
93
* Returns the JSON model as a JSON string
94
* @return JSON model as string
95
*/
96
public String jsonString();
97
98
/**
99
* Reads the given path from this context
100
* @param path JsonPath expression
101
* @param filters Optional predicates for filtering
102
* @return Result matching the path
103
*/
104
public <T> T read(String path, Predicate... filters);
105
106
/**
107
* Reads the given path with type mapping
108
* @param path JsonPath expression
109
* @param type Expected return type
110
* @param filters Optional predicates for filtering
111
* @return Result mapped to specified type
112
*/
113
public <T> T read(String path, Class<T> type, Predicate... filters);
114
115
/**
116
* Reads using a compiled JsonPath
117
* @param path Compiled JsonPath instance
118
* @return Result matching the path
119
*/
120
public <T> T read(JsonPath path);
121
122
/**
123
* Reads using a compiled JsonPath with type mapping
124
* @param path Compiled JsonPath instance
125
* @param type Expected return type
126
* @return Result mapped to specified type
127
*/
128
public <T> T read(JsonPath path, Class<T> type);
129
130
/**
131
* Reads using a compiled JsonPath with generic type reference
132
* @param path Compiled JsonPath instance
133
* @param typeRef Type reference for generic types
134
* @return Result mapped to specified generic type
135
*/
136
public <T> T read(JsonPath path, TypeRef<T> typeRef);
137
138
/**
139
* Reads with generic type reference
140
* @param path JsonPath expression
141
* @param typeRef Type reference for generic types
142
* @return Result mapped to specified generic type
143
*/
144
public <T> T read(String path, TypeRef<T> typeRef);
145
```
146
147
**Usage Examples:**
148
149
```java
150
import com.jayway.jsonpath.JsonPath;
151
import com.jayway.jsonpath.DocumentContext;
152
import com.jayway.jsonpath.TypeRef;
153
import java.util.List;
154
import java.util.Map;
155
156
DocumentContext context = JsonPath.parse(json);
157
158
// Basic reading
159
String name = context.read("$.users[0].name");
160
List<String> allNames = context.read("$.users[*].name");
161
162
// Type-safe reading
163
List<Integer> ages = context.read("$.users[*].age", List.class);
164
165
// Generic type reference
166
TypeRef<List<Map<String, Object>>> typeRef = new TypeRef<List<Map<String, Object>>>() {};
167
List<Map<String, Object>> users = context.read("$.users", typeRef);
168
169
// Access underlying data
170
Map<String, Object> jsonData = context.json();
171
String jsonString = context.jsonString();
172
```
173
174
### Writing Operations
175
176
Modifying the parsed JSON document by setting, adding, deleting, or transforming values.
177
178
```java { .api }
179
/**
180
* Sets a value at the specified path
181
* @param path JsonPath expression
182
* @param newValue Value to set
183
* @param filters Optional predicates for filtering
184
* @return Updated DocumentContext
185
*/
186
public DocumentContext set(String path, Object newValue, Predicate... filters);
187
188
/**
189
* Sets a value using compiled JsonPath
190
* @param path Compiled JsonPath instance
191
* @param newValue Value to set
192
* @return Updated DocumentContext
193
*/
194
public DocumentContext set(JsonPath path, Object newValue);
195
196
/**
197
* Transforms values using a mapping function
198
* @param path JsonPath expression
199
* @param mapFunction Function to transform values
200
* @param filters Optional predicates for filtering
201
* @return Updated DocumentContext
202
*/
203
public DocumentContext map(String path, MapFunction mapFunction, Predicate... filters);
204
205
/**
206
* Transforms values using compiled JsonPath
207
* @param path Compiled JsonPath instance
208
* @param mapFunction Function to transform values
209
* @return Updated DocumentContext
210
*/
211
public DocumentContext map(JsonPath path, MapFunction mapFunction);
212
213
/**
214
* Deletes values at the specified path
215
* @param path JsonPath expression
216
* @param filters Optional predicates for filtering
217
* @return Updated DocumentContext
218
*/
219
public DocumentContext delete(String path, Predicate... filters);
220
221
/**
222
* Deletes values using compiled JsonPath
223
* @param path Compiled JsonPath instance
224
* @return Updated DocumentContext
225
*/
226
public DocumentContext delete(JsonPath path);
227
228
/**
229
* Adds a value to an array at the specified path
230
* @param path JsonPath expression pointing to array
231
* @param value Value to add
232
* @param filters Optional predicates for filtering
233
* @return Updated DocumentContext
234
*/
235
public DocumentContext add(String path, Object value, Predicate... filters);
236
237
/**
238
* Adds a value to an array using compiled JsonPath
239
* @param path Compiled JsonPath instance pointing to array
240
* @param value Value to add
241
* @return Updated DocumentContext
242
*/
243
public DocumentContext add(JsonPath path, Object value);
244
245
/**
246
* Adds or updates a property in an object
247
* @param path JsonPath expression pointing to object
248
* @param key Property name
249
* @param value Property value
250
* @param filters Optional predicates for filtering
251
* @return Updated DocumentContext
252
*/
253
public DocumentContext put(String path, String key, Object value, Predicate... filters);
254
255
/**
256
* Adds or updates a property using compiled JsonPath
257
* @param path Compiled JsonPath instance pointing to object
258
* @param key Property name
259
* @param value Property value
260
* @return Updated DocumentContext
261
*/
262
public DocumentContext put(JsonPath path, String key, Object value);
263
264
/**
265
* Renames a property key
266
* @param path JsonPath expression pointing to object containing the key
267
* @param oldKeyName Current key name
268
* @param newKeyName New key name
269
* @param filters Optional predicates for filtering
270
* @return Updated DocumentContext
271
*/
272
public DocumentContext renameKey(String path, String oldKeyName, String newKeyName, Predicate... filters);
273
274
/**
275
* Renames a property key using compiled JsonPath
276
* @param path Compiled JsonPath instance pointing to object
277
* @param oldKeyName Current key name
278
* @param newKeyName New key name
279
* @return Updated DocumentContext
280
*/
281
public DocumentContext renameKey(JsonPath path, String oldKeyName, String newKeyName);
282
```
283
284
**Usage Examples:**
285
286
```java
287
import com.jayway.jsonpath.JsonPath;
288
import com.jayway.jsonpath.DocumentContext;
289
import com.jayway.jsonpath.MapFunction;
290
291
String json = "{ \"users\": [{ \"name\": \"Alice\", \"age\": 30 }], \"metadata\": {} }";
292
DocumentContext context = JsonPath.parse(json);
293
294
// Set values
295
context.set("$.users[0].age", 31);
296
context.set("$.metadata.lastUpdated", "2024-01-01");
297
298
// Delete values
299
context.delete("$.users[0].age");
300
301
// Add to arrays
302
context.add("$.users", Map.of("name", "Bob", "age", 25));
303
304
// Add/update object properties
305
context.put("$.metadata", "version", "1.0");
306
context.put("$.metadata", "author", "System");
307
308
// Rename keys
309
context.renameKey("$.users[0]", "name", "fullName");
310
311
// Transform values with mapping function
312
context.map("$.users[*].age", new MapFunction() {
313
public Object map(Object currentValue, Configuration configuration) {
314
return ((Integer) currentValue) + 1; // Add 1 to all ages
315
}
316
});
317
318
// Lambda version (Java 8+)
319
context.map("$.users[*].name", (current, config) ->
320
((String) current).toUpperCase());
321
322
// Get updated JSON
323
String updatedJson = context.jsonString();
324
```
325
326
### Evaluation Control
327
328
Methods for controlling the evaluation process with limits and listeners.
329
330
```java { .api }
331
/**
332
* Limits the number of results returned by evaluation
333
* @param maxResults Maximum number of results to return
334
* @return ReadContext with limit applied
335
*/
336
public ReadContext limit(int maxResults);
337
338
/**
339
* Adds evaluation listeners to monitor path evaluation
340
* @param listener Listeners to add for evaluation events
341
* @return ReadContext with listeners added
342
*/
343
public ReadContext withListeners(EvaluationListener... listener);
344
```
345
346
**Usage Examples:**
347
348
```java
349
import com.jayway.jsonpath.JsonPath;
350
import com.jayway.jsonpath.DocumentContext;
351
import com.jayway.jsonpath.EvaluationListener;
352
353
DocumentContext context = JsonPath.parse(largeJsonArray);
354
355
// Limit results to first 10 matches
356
List<String> limitedResults = context
357
.limit(10)
358
.read("$.items[*].name");
359
360
// Add evaluation listener
361
List<String> names = context
362
.withListeners(new EvaluationListener() {
363
public EvaluationContinuation resultFound(FoundResult found) {
364
System.out.println("Found: " + found.result() + " at " + found.path());
365
return EvaluationContinuation.CONTINUE;
366
}
367
})
368
.read("$.users[*].name");
369
```
370
371
### Advanced Reading Operations
372
373
Additional ReadContext methods for performance optimization and monitoring.
374
375
```java { .api }
376
/**
377
* Limits the number of results returned from path evaluation
378
* @param maxResults Maximum number of results to return
379
* @return ReadContext with result limit applied
380
*/
381
public ReadContext limit(int maxResults);
382
383
/**
384
* Adds evaluation listeners to monitor path evaluation progress
385
* @param listeners Listeners to receive evaluation callbacks
386
* @return ReadContext with listeners attached
387
*/
388
public ReadContext withListeners(EvaluationListener... listeners);
389
```
390
391
**Usage Examples:**
392
393
```java
394
import com.jayway.jsonpath.JsonPath;
395
import com.jayway.jsonpath.DocumentContext;
396
import com.jayway.jsonpath.EvaluationListener;
397
import java.util.List;
398
399
String json = "{ \"items\": [" +
400
"{ \"id\": 1, \"name\": \"Item 1\" }," +
401
"{ \"id\": 2, \"name\": \"Item 2\" }," +
402
"{ \"id\": 3, \"name\": \"Item 3\" }," +
403
"{ \"id\": 4, \"name\": \"Item 4\" }," +
404
"{ \"id\": 5, \"name\": \"Item 5\" }" +
405
"] }";
406
407
DocumentContext context = JsonPath.parse(json);
408
409
// Limit results to first 3 items
410
List<Object> limitedResults = context.limit(3).read("$.items[*]");
411
// Returns only first 3 items
412
413
// Create evaluation listener
414
EvaluationListener listener = new EvaluationListener() {
415
@Override
416
public EvaluationContinuation resultFound(FoundResult found) {
417
System.out.println("Found result at index " + found.index() +
418
" with path " + found.path() +
419
": " + found.result());
420
421
// Continue evaluation for all results
422
return EvaluationContinuation.CONTINUE;
423
424
// Or abort after first result
425
// return EvaluationContinuation.ABORT;
426
}
427
};
428
429
// Use listener to monitor evaluation
430
List<Object> monitoredResults = context.withListeners(listener).read("$.items[*].name");
431
432
// Combine limit and listeners
433
List<Object> combinedResults = context
434
.limit(2)
435
.withListeners(listener)
436
.read("$.items[*]");
437
```
438
439
### Evaluation Listener Interface
440
441
Interface for monitoring JsonPath evaluation progress and controlling execution.
442
443
```java { .api }
444
/**
445
* Interface for receiving callbacks during path evaluation
446
*/
447
public interface EvaluationListener {
448
/**
449
* Called when a result is found during path evaluation
450
* @param found Information about the found result
451
* @return Continuation instruction for evaluation
452
*/
453
EvaluationContinuation resultFound(FoundResult found);
454
455
/**
456
* Enumeration controlling evaluation continuation
457
*/
458
public enum EvaluationContinuation {
459
/** Continue evaluation to find more results */
460
CONTINUE,
461
/** Abort evaluation immediately */
462
ABORT
463
}
464
465
/**
466
* Interface providing information about a found result
467
*/
468
public interface FoundResult {
469
/**
470
* Index of the result in the evaluation sequence
471
* @return Zero-based index of this result
472
*/
473
int index();
474
475
/**
476
* Path to the found result
477
* @return JsonPath string to this result
478
*/
479
String path();
480
481
/**
482
* The actual result value
483
* @return Found result object
484
*/
485
Object result();
486
}
487
}
488
```
489
490
**Usage Examples:**
491
492
```java
493
import com.jayway.jsonpath.EvaluationListener;
494
import com.jayway.jsonpath.EvaluationListener.EvaluationContinuation;
495
import com.jayway.jsonpath.EvaluationListener.FoundResult;
496
497
// Simple logging listener
498
EvaluationListener loggingListener = new EvaluationListener() {
499
@Override
500
public EvaluationContinuation resultFound(FoundResult found) {
501
System.out.println("Result " + found.index() + ": " + found.result());
502
return EvaluationContinuation.CONTINUE;
503
}
504
};
505
506
// Early termination listener (stops after 3 results)
507
EvaluationListener earlyTerminationListener = new EvaluationListener() {
508
@Override
509
public EvaluationContinuation resultFound(FoundResult found) {
510
if (found.index() >= 2) { // Stop after 3 results (0, 1, 2)
511
return EvaluationContinuation.ABORT;
512
}
513
return EvaluationContinuation.CONTINUE;
514
}
515
};
516
517
// Filtering listener (only continues for specific results)
518
EvaluationListener filteringListener = new EvaluationListener() {
519
@Override
520
public EvaluationContinuation resultFound(FoundResult found) {
521
Object result = found.result();
522
if (result instanceof Map) {
523
Map<String, Object> map = (Map<String, Object>) result;
524
Object price = map.get("price");
525
if (price instanceof Number && ((Number) price).doubleValue() > 10.0) {
526
System.out.println("Expensive item found: " + result);
527
}
528
}
529
return EvaluationContinuation.CONTINUE;
530
}
531
};
532
533
// Use listeners with document context
534
DocumentContext context = JsonPath.parse(json);
535
List<Object> results = context
536
.withListeners(loggingListener, filteringListener)
537
.read("$.store.book[*]");
538
```
539
540
### ParseContext Interface
541
542
Interface for creating DocumentContext instances with different parsing configurations.
543
544
```java { .api }
545
/**
546
* Interface for parsing JSON from various sources
547
*/
548
public interface ParseContext {
549
/**
550
* Parse JSON string
551
* @param json JSON string to parse
552
* @return DocumentContext for operations
553
*/
554
DocumentContext parse(String json);
555
556
/**
557
* Parse JSON object
558
* @param json Parsed JSON object
559
* @return DocumentContext for operations
560
*/
561
DocumentContext parse(Object json);
562
563
/**
564
* Parse from input stream
565
* @param json Input stream containing JSON
566
* @return DocumentContext for operations
567
*/
568
DocumentContext parse(InputStream json);
569
570
/**
571
* Parse from input stream with charset
572
* @param json Input stream containing JSON
573
* @param charset Character encoding to use
574
* @return DocumentContext for operations
575
*/
576
DocumentContext parse(InputStream json, String charset);
577
578
/**
579
* Parse from file
580
* @param json File containing JSON data
581
* @return DocumentContext for operations
582
* @throws IOException If file cannot be read
583
*/
584
DocumentContext parse(File json) throws IOException;
585
586
/**
587
* Parse UTF-8 encoded bytes
588
* @param json Byte array containing UTF-8 JSON
589
* @return DocumentContext for operations
590
*/
591
DocumentContext parseUtf8(byte[] json);
592
}
593
```