forked from json-path/JsonPath
/
JsonPath.java
715 lines (651 loc) · 25.5 KB
/
JsonPath.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/*
* Copyright 2011 the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jayway.jsonpath;
import com.jayway.jsonpath.internal.*;
import com.jayway.jsonpath.internal.path.PathCompiler;
import com.jayway.jsonpath.spi.json.JsonProvider;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import static com.jayway.jsonpath.Option.ALWAYS_RETURN_LIST;
import static com.jayway.jsonpath.Option.AS_PATH_LIST;
import static com.jayway.jsonpath.internal.Utils.*;
/**
* <p/>
* JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPath is
* available in many programming languages such as Javascript, Python and PHP.
* <p/>
* JsonPath allows you to compile a json path string to use it many times or to compile and apply in one
* single on demand operation.
* <p/>
* Given the Json document:
* <p/>
* <pre>
* String json =
* "{
* "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
* }
* ],
* "bicycle":
* {
* "color": "red",
* "price": 19.95
* }
* }
* }";
* </pre>
* <p/>
* A JsonPath can be compiled and used as shown:
* <p/>
* <code>
* JsonPath path = JsonPath.compile("$.store.book[1]");
* <br/>
* List<Object> books = path.read(json);
* </code>
* </p>
* Or:
* <p/>
* <code>
* List<Object> authors = JsonPath.read(json, "$.store.book[*].author")
* </code>
* <p/>
* If the json path returns a single value (is definite):
* </p>
* <code>
* String author = JsonPath.read(json, "$.store.book[1].author")
* </code>
*/
public class JsonPath {
private final Path path;
private JsonPath(String jsonPath, Predicate[] filters) {
notNull(jsonPath, "path can not be null");
this.path = PathCompiler.compile(jsonPath, filters);
}
/**
* Returns the string representation of this JsonPath
*
* @return path as String
*/
public String getPath() {
return this.path.toString();
}
/**
* @see JsonPath#isDefinite()
*/
public static boolean isPathDefinite(String path) {
return compile(path).isDefinite();
}
/**
* Checks if a path points to a single item or if it potentially returns multiple items
* <p/>
* a path is considered <strong>not</strong> definite if it contains a scan fragment ".."
* or an array position fragment that is not based on a single index
* <p/>
* <p/>
* definite path examples are:
* <p/>
* $store.book
* $store.book[1].title
* <p/>
* not definite path examples are:
* <p/>
* $..book
* $.store.book[*]
* $.store.book[1,2]
* $.store.book[?(@.category = 'fiction')]
*
* @return true if path is definite (points to single item)
*/
public boolean isDefinite() {
return path.isDefinite();
}
/**
* Applies this JsonPath to the provided json document.
* Note that the document must be identified as either a List or Map by
* the {@link JsonProvider}
*
* @param jsonObject a container Object
* @param <T> expected return type
* @return object(s) matched by the given path
*/
@SuppressWarnings({"unchecked"})
public <T> T read(Object jsonObject) {
return read(jsonObject, Configuration.defaultConfiguration());
}
/**
* Applies this JsonPath to the provided json document.
* Note that the document must be identified as either a List or Map by
* the {@link JsonProvider}
*
* @param jsonObject a container Object
* @param configuration configuration to use
* @param <T> expected return type
* @return object(s) matched by the given path
*/
@SuppressWarnings("unchecked")
public <T> T read(Object jsonObject, Configuration configuration) {
boolean optAsPathList = configuration.containsOption(AS_PATH_LIST);
boolean optAlwaysReturnList = configuration.containsOption(Option.ALWAYS_RETURN_LIST);
boolean optSuppressExceptions = configuration.containsOption(Option.SUPPRESS_EXCEPTIONS);
try {
if (path.isFunctionPath()) {
if (optAsPathList || optAlwaysReturnList) {
throw new JsonPathException("Options " + AS_PATH_LIST + " and " + ALWAYS_RETURN_LIST + " are not allowed when using path functions!");
}
return path.evaluate(jsonObject, jsonObject, configuration).getValue(true);
} else if (optAsPathList) {
return (T) path.evaluate(jsonObject, jsonObject, configuration).getPath();
} else {
Object res = path.evaluate(jsonObject, jsonObject, configuration).getValue(false);
if (optAlwaysReturnList && path.isDefinite()) {
Object array = configuration.jsonProvider().createArray();
configuration.jsonProvider().setArrayIndex(array, 0, res);
return (T) array;
} else {
return (T) res;
}
}
} catch (RuntimeException e) {
if (!optSuppressExceptions) {
throw e;
} else {
if (optAsPathList) {
return (T) configuration.jsonProvider().createArray();
} else {
if (optAlwaysReturnList) {
return (T) configuration.jsonProvider().createArray();
} else {
return (T) (path.isDefinite() ? null : configuration.jsonProvider().createArray());
}
}
}
}
}
/**
* Set the value this path points to in the provided jsonObject
*
* @param jsonObject a json object
* @param configuration configuration to use
* @param <T> expected return type
* @return the updated jsonObject or the path list to updated objects if option AS_PATH_LIST is set.
*/
public <T> T set(Object jsonObject, Object newVal, Configuration configuration) {
notNull(jsonObject, "json can not be null");
notNull(configuration, "configuration can not be null");
EvaluationContext evaluationContext = path.evaluate(jsonObject, jsonObject, configuration, true);
for (PathRef updateOperation : evaluationContext.updateOperations()) {
updateOperation.set(newVal, configuration);
}
return resultByConfiguration(jsonObject, configuration, evaluationContext);
}
/**
* Replaces the value on the given path with the result of the {@link MapFunction}.
*
* @param jsonObject a json object
* @param mapFunction Converter object to be invoked
* @param configuration configuration to use
* @return the updated jsonObject or the path list to updated objects if option AS_PATH_LIST is set.
*/
public <T> T map(Object jsonObject, MapFunction mapFunction, Configuration configuration) {
notNull(jsonObject, "json can not be null");
notNull(configuration, "configuration can not be null");
notNull(mapFunction, "mapFunction can not be null");
boolean optAsPathList = configuration.containsOption(AS_PATH_LIST);
boolean optAlwaysReturnList = configuration.containsOption(Option.ALWAYS_RETURN_LIST);
boolean optSuppressExceptions = configuration.containsOption(Option.SUPPRESS_EXCEPTIONS);
try {
EvaluationContext evaluationContext = path.evaluate(jsonObject, jsonObject, configuration, true);
for (PathRef updateOperation : evaluationContext.updateOperations()) {
updateOperation.convert(mapFunction, configuration);
}
return resultByConfiguration(jsonObject, configuration, evaluationContext);
}catch (RuntimeException e) {
if (!optSuppressExceptions) {
throw e;
} else {
if (optAsPathList) {
return (T) configuration.jsonProvider().createArray();
} else {
if (optAlwaysReturnList) {
return (T) configuration.jsonProvider().createArray();
} else {
return (T) (path.isDefinite() ? null : configuration.jsonProvider().createArray());
}
}
}
}
}
/**
* Deletes the object this path points to in the provided jsonObject
*
* @param jsonObject a json object
* @param configuration configuration to use
* @param <T> expected return type
* @return the updated jsonObject or the path list to deleted objects if option AS_PATH_LIST is set.
*/
public <T> T delete(Object jsonObject, Configuration configuration) {
notNull(jsonObject, "json can not be null");
notNull(configuration, "configuration can not be null");
EvaluationContext evaluationContext = path.evaluate(jsonObject, jsonObject, configuration, true);
for (PathRef updateOperation : evaluationContext.updateOperations()) {
updateOperation.delete(configuration);
}
return resultByConfiguration(jsonObject, configuration, evaluationContext);
}
/**
* Adds a new value to the Array this path points to in the provided jsonObject
*
* @param jsonObject a json object
* @param value the value to add
* @param configuration configuration to use
* @param <T> expected return type
* @return the updated jsonObject or the path list to updated object if option AS_PATH_LIST is set.
*/
public <T> T add(Object jsonObject, Object value, Configuration configuration) {
notNull(jsonObject, "json can not be null");
notNull(configuration, "configuration can not be null");
EvaluationContext evaluationContext = path.evaluate(jsonObject, jsonObject, configuration, true);
for (PathRef updateOperation : evaluationContext.updateOperations()) {
updateOperation.add(value, configuration);
}
return resultByConfiguration(jsonObject, configuration, evaluationContext);
}
/**
* Adds or updates the Object this path points to in the provided jsonObject with a key with a value
*
* @param jsonObject a json object
* @param key the key to add or update
* @param value the new value
* @param configuration configuration to use
* @param <T> expected return type
* @return the updated jsonObject or the path list to updated objects if option AS_PATH_LIST is set.
*/
public <T> T put(Object jsonObject, String key, Object value, Configuration configuration) {
notNull(jsonObject, "json can not be null");
notEmpty(key, "key can not be null or empty");
notNull(configuration, "configuration can not be null");
EvaluationContext evaluationContext = path.evaluate(jsonObject, jsonObject, configuration, true);
for (PathRef updateOperation : evaluationContext.updateOperations()) {
updateOperation.put(key, value, configuration);
}
return resultByConfiguration(jsonObject, configuration, evaluationContext);
}
public <T> T renameKey(Object jsonObject, String oldKeyName, String newKeyName, Configuration configuration) {
notNull(jsonObject, "json can not be null");
notEmpty(newKeyName, "newKeyName can not be null or empty");
notNull(configuration, "configuration can not be null");
EvaluationContext evaluationContext = path.evaluate(jsonObject, jsonObject, configuration, true);
for (PathRef updateOperation : evaluationContext.updateOperations()) {
updateOperation.renameKey(oldKeyName, newKeyName, configuration);
}
return resultByConfiguration(jsonObject, configuration, evaluationContext);
}
/**
* Applies this JsonPath to the provided json string
*
* @param json a json string
* @param <T> expected return type
* @return list of objects matched by the given path
*/
@SuppressWarnings({"unchecked"})
public <T> T read(String json) {
return read(json, Configuration.defaultConfiguration());
}
/**
* Applies this JsonPath to the provided json string
*
* @param json a json string
* @param configuration configuration to use
* @param <T> expected return type
* @return list of objects matched by the given path
*/
@SuppressWarnings({"unchecked"})
public <T> T read(String json, Configuration configuration) {
notEmpty(json, "json can not be null or empty");
notNull(configuration, "jsonProvider can not be null");
return read(configuration.jsonProvider().parse(json), configuration);
}
/**
* Applies this JsonPath to the provided json URL
*
* @param jsonURL url to read from
* @param <T> expected return type
* @return list of objects matched by the given path
* @throws IOException
*/
@SuppressWarnings({"unchecked"})
public <T> T read(URL jsonURL) throws IOException {
return read(jsonURL, Configuration.defaultConfiguration());
}
/**
* Applies this JsonPath to the provided json file
*
* @param jsonFile file to read from
* @param <T> expected return type
* @return list of objects matched by the given path
* @throws IOException
*/
@SuppressWarnings({"unchecked"})
public <T> T read(File jsonFile) throws IOException {
return read(jsonFile, Configuration.defaultConfiguration());
}
/**
* Applies this JsonPath to the provided json file
*
* @param jsonFile file to read from
* @param configuration configuration to use
* @param <T> expected return type
* @return list of objects matched by the given path
* @throws IOException
*/
@SuppressWarnings({"unchecked"})
public <T> T read(File jsonFile, Configuration configuration) throws IOException {
notNull(jsonFile, "json file can not be null");
isTrue(jsonFile.exists(), "json file does not exist");
notNull(configuration, "jsonProvider can not be null");
FileInputStream fis = null;
try {
fis = new FileInputStream(jsonFile);
return read(fis, configuration);
} finally {
Utils.closeQuietly(fis);
}
}
/**
* Applies this JsonPath to the provided json input stream
*
* @param jsonInputStream input stream to read from
* @param <T> expected return type
* @return list of objects matched by the given path
* @throws IOException
*/
@SuppressWarnings({"unchecked"})
public <T> T read(InputStream jsonInputStream) throws IOException {
return read(jsonInputStream, Configuration.defaultConfiguration());
}
/**
* Applies this JsonPath to the provided json input stream
*
* @param jsonInputStream input stream to read from
* @param configuration configuration to use
* @param <T> expected return type
* @return list of objects matched by the given path
* @throws IOException
*/
@SuppressWarnings({"unchecked"})
public <T> T read(InputStream jsonInputStream, Configuration configuration) throws IOException {
notNull(jsonInputStream, "json input stream can not be null");
notNull(configuration, "configuration can not be null");
return read(jsonInputStream, "UTF-8", configuration);
}
/**
* Applies this JsonPath to the provided json input stream
*
* @param jsonInputStream input stream to read from
* @param configuration configuration to use
* @param <T> expected return type
* @return list of objects matched by the given path
* @throws IOException
*/
@SuppressWarnings({"unchecked"})
public <T> T read(InputStream jsonInputStream, String charset, Configuration configuration) throws IOException {
notNull(jsonInputStream, "json input stream can not be null");
notNull(charset, "charset can not be null");
notNull(configuration, "configuration can not be null");
try {
return read(configuration.jsonProvider().parse(jsonInputStream, charset), configuration);
} finally {
Utils.closeQuietly(jsonInputStream);
}
}
// --------------------------------------------------------
//
// Static factory methods
//
// --------------------------------------------------------
/**
* Compiles a JsonPath
*
* @param jsonPath to compile
* @param filters filters to be applied to the filter place holders [?] in the path
* @return compiled JsonPath
*/
public static JsonPath compile(String jsonPath, Predicate... filters) {
notEmpty(jsonPath, "json can not be null or empty");
return new JsonPath(jsonPath, filters);
}
// --------------------------------------------------------
//
// Static utility functions
//
// --------------------------------------------------------
/**
* Creates a new JsonPath and applies it to the provided Json object
*
* @param json a json object
* @param jsonPath the json path
* @param filters filters to be applied to the filter place holders [?] in the path
* @param <T> expected return type
* @return list of objects matched by the given path
*/
@SuppressWarnings({"unchecked"})
public static <T> T read(Object json, String jsonPath, Predicate... filters) {
return parse(json).read(jsonPath, filters);
}
/**
* Creates a new JsonPath and applies it to the provided Json string
*
* @param json a json string
* @param jsonPath the json path
* @param filters filters to be applied to the filter place holders [?] in the path
* @param <T> expected return type
* @return list of objects matched by the given path
*/
@SuppressWarnings({"unchecked"})
public static <T> T read(String json, String jsonPath, Predicate... filters) {
return new ParseContextImpl().parse(json).read(jsonPath, filters);
}
/**
* Creates a new JsonPath and applies it to the provided Json object
*
* @param jsonURL url pointing to json doc
* @param jsonPath the json path
* @param filters filters to be applied to the filter place holders [?] in the path
* @param <T> expected return type
* @return list of objects matched by the given path
*/
@SuppressWarnings({"unchecked"})
@Deprecated
public static <T> T read(URL jsonURL, String jsonPath, Predicate... filters) throws IOException {
return new ParseContextImpl().parse(jsonURL).read(jsonPath, filters);
}
/**
* Creates a new JsonPath and applies it to the provided Json object
*
* @param jsonFile json file
* @param jsonPath the json path
* @param filters filters to be applied to the filter place holders [?] in the path
* @param <T> expected return type
* @return list of objects matched by the given path
*/
@SuppressWarnings({"unchecked"})
public static <T> T read(File jsonFile, String jsonPath, Predicate... filters) throws IOException {
return new ParseContextImpl().parse(jsonFile).read(jsonPath, filters);
}
/**
* Creates a new JsonPath and applies it to the provided Json object
*
* @param jsonInputStream json input stream
* @param jsonPath the json path
* @param filters filters to be applied to the filter place holders [?] in the path
* @param <T> expected return type
* @return list of objects matched by the given path
*/
@SuppressWarnings({"unchecked"})
public static <T> T read(InputStream jsonInputStream, String jsonPath, Predicate... filters) throws IOException {
return new ParseContextImpl().parse(jsonInputStream).read(jsonPath, filters);
}
// --------------------------------------------------------
//
// Static Fluent API
//
// --------------------------------------------------------
/**
* Creates a {@link ParseContext} that can be used to parse JSON input. The parse context
* is as thread safe as the underlying {@link JsonProvider}. Note that not all JsonProvider are
* thread safe.
*
* @param configuration configuration to use when parsing JSON
* @return a parsing context based on given configuration
*/
public static ParseContext using(Configuration configuration) {
return new ParseContextImpl(configuration);
}
/**
* Creates a {@link ParseContext} that will parse a given JSON input.
*
* @param provider jsonProvider to use when parsing JSON
* @return a parsing context based on given jsonProvider
*/
@Deprecated
public static ParseContext using(JsonProvider provider) {
return new ParseContextImpl(Configuration.builder().jsonProvider(provider).build());
}
/**
* Parses the given JSON input using the default {@link Configuration} and
* returns a {@link DocumentContext} for path evaluation
*
* @param json input
* @return a read context
*/
public static DocumentContext parse(Object json) {
return new ParseContextImpl().parse(json);
}
/**
* Parses the given JSON input using the default {@link Configuration} and
* returns a {@link DocumentContext} for path evaluation
*
* @param json string
* @return a read context
*/
public static DocumentContext parse(String json) {
return new ParseContextImpl().parse(json);
}
/**
* Parses the given JSON input using the default {@link Configuration} and
* returns a {@link DocumentContext} for path evaluation
*
* @param json stream
* @return a read context
*/
public static DocumentContext parse(InputStream json) {
return new ParseContextImpl().parse(json);
}
/**
* Parses the given JSON input using the default {@link Configuration} and
* returns a {@link DocumentContext} for path evaluation
*
* @param json file
* @return a read context
*/
public static DocumentContext parse(File json) throws IOException {
return new ParseContextImpl().parse(json);
}
/**
* Parses the given JSON input using the default {@link Configuration} and
* returns a {@link DocumentContext} for path evaluation
*
* @param json url
* @return a read context
*/
@Deprecated
public static DocumentContext parse(URL json) throws IOException {
return new ParseContextImpl().parse(json);
}
/**
* Parses the given JSON input using the provided {@link Configuration} and
* returns a {@link DocumentContext} for path evaluation
*
* @param json input
* @return a read context
*/
public static DocumentContext parse(Object json, Configuration configuration) {
return new ParseContextImpl(configuration).parse(json);
}
/**
* Parses the given JSON input using the provided {@link Configuration} and
* returns a {@link DocumentContext} for path evaluation
*
* @param json input
* @return a read context
*/
public static DocumentContext parse(String json, Configuration configuration) {
return new ParseContextImpl(configuration).parse(json);
}
/**
* Parses the given JSON input using the provided {@link Configuration} and
* returns a {@link DocumentContext} for path evaluation
*
* @param json input
* @return a read context
*/
public static DocumentContext parse(InputStream json, Configuration configuration) {
return new ParseContextImpl(configuration).parse(json);
}
/**
* Parses the given JSON input using the provided {@link Configuration} and
* returns a {@link DocumentContext} for path evaluation
*
* @param json input
* @return a read context
*/
public static DocumentContext parse(File json, Configuration configuration) throws IOException {
return new ParseContextImpl(configuration).parse(json);
}
/**
* Parses the given JSON input using the provided {@link Configuration} and
* returns a {@link DocumentContext} for path evaluation
*
* @param json input
* @return a read context
*/
@Deprecated
public static DocumentContext parse(URL json, Configuration configuration) throws IOException {
return new ParseContextImpl(configuration).parse(json);
}
private <T> T resultByConfiguration(Object jsonObject, Configuration configuration, EvaluationContext evaluationContext) {
if(configuration.containsOption(AS_PATH_LIST)){
return (T)evaluationContext.getPathList();
} else {
return (T) jsonObject;
}
}
}