1mod atom;
2mod comparable;
3mod comparison;
4mod context;
5mod filter;
6mod jp_query;
7pub mod queryable;
8mod segment;
9mod selector;
10pub mod state;
11mod test;
12mod test_function;
13
14use crate::parser::errors::JsonPathError;
15use crate::parser::model::JpQuery;
16use crate::parser::{parse_json_path, Parsed};
17use crate::query::queryable::Queryable;
18use crate::query::state::{Data, Pointer};
19use state::State;
20use std::borrow::Cow;
21
22pub use context::JsonPathEvalContext;
23
24pub type QueryPath = String;
26
27pub type Queried<T> = Result<T, JsonPathError>;
29
30pub trait Query {
32 fn process<'a, T: Queryable>(&self, state: State<'a, T>) -> State<'a, T> {
34 self.process_with_context(state, &mut JsonPathEvalContext::default())
35 }
36
37 fn process_with_context<'a, T: Queryable>(
39 &self,
40 state: State<'a, T>,
41 ctx: &mut JsonPathEvalContext,
42 ) -> State<'a, T>;
43}
44
45#[derive(Debug, Clone, PartialEq)]
48pub struct QueryRef<'a, T: Queryable> {
49 pub val: &'a T,
50 pub path: QueryPath,
51}
52
53impl<'a, T: Queryable> QueryRef<'a, T> {
54 pub fn val(self) -> &'a T {
55 self.val
56 }
57 pub fn path(self) -> QueryPath {
58 self.path
59 }
60}
61
62impl<'a, T: Queryable> From<(&'a T, QueryPath)> for QueryRef<'a, T> {
63 fn from((val, path): (&'a T, QueryPath)) -> Self {
64 QueryRef { val, path }
65 }
66}
67impl<'a, T: Queryable> From<(&'a T, &str)> for QueryRef<'a, T> {
68 fn from((val, path): (&'a T, &str)) -> Self {
69 QueryRef {
70 val,
71 path: path.to_string(),
72 }
73 }
74}
75
76impl<'a, T: Queryable> From<Pointer<'a, T>> for QueryRef<'a, T> {
77 fn from(pointer: Pointer<'a, T>) -> Self {
78 QueryRef {
79 val: pointer.inner,
80 path: pointer.path,
81 }
82 }
83}
84
85pub fn js_path<'a, T: Queryable>(path: &str, value: &'a T) -> Queried<Vec<QueryRef<'a, T>>> {
88 js_path_process(&parse_json_path(path)?, value)
89}
90
91pub fn js_path_process<'a, 'b, T: Queryable>(
94 path: &'b JpQuery,
95 value: &'a T,
96) -> Queried<Vec<QueryRef<'a, T>>> {
97 path.execute_with_context(value, &mut JsonPathEvalContext::default())
98}
99
100impl JpQuery {
101 pub fn execute_with_context<'a, T: Queryable>(
104 &self,
105 value: &'a T,
106 ctx: &mut JsonPathEvalContext,
107 ) -> Queried<Vec<QueryRef<'a, T>>> {
108 match self.process_with_context(State::root(value), ctx).data {
109 Data::Ref(p) => Ok(vec![p.into()]),
110 Data::Refs(refs) => Ok(refs.into_iter().map(Into::into).collect()),
111 Data::Value(v) => Err(v.into()),
112 Data::Nothing => Ok(vec![]),
113 }
114 }
115}
116
117pub fn js_path_vals<'a, T: Queryable>(path: &str, value: &'a T) -> Queried<Vec<&'a T>> {
119 Ok(js_path(path, value)?
120 .into_iter()
121 .map(|r| r.val)
122 .collect::<Vec<_>>())
123}
124
125pub fn js_path_path<T: Queryable>(path: &str, value: &T) -> Queried<Vec<QueryPath>> {
127 Ok(js_path(path, value)?
128 .into_iter()
129 .map(|r| r.path)
130 .collect::<Vec<_>>())
131}
132
133#[cfg(test)]
134mod tests {
135 use crate::parser::errors::JsonPathError;
136 use crate::parser::{parse_json_path, Parsed};
137 use crate::query::queryable::Queryable;
138 use crate::query::{js_path, js_path_process, JsonPathEvalContext, Queried, QueryRef};
139 use crate::JsonPath;
140 use serde_json::{json, Value};
141
142 fn test<'a, R>(json: &'a str, path: &str, expected: Vec<R>) -> Parsed<()>
143 where
144 R: Into<QueryRef<'a, Value>>,
145 {
146 let json: Value = serde_json::from_str(json).map_err(|v| JsonPathError::NoRulePath)?;
147 let expected: Vec<QueryRef<'a, Value>> = expected.into_iter().map(|v| v.into()).collect();
148 assert_eq!(json.query_with_path(path)?, expected);
149
150 Ok(())
151 }
152
153 fn template_json<'a>() -> &'a str {
154 r#" {"store": { "book": [
155 {
156 "category": "reference",
157 "author": "Nigel Rees",
158 "title": "Sayings of the Century",
159 "price": 8.95
160 },
161 {
162 "category": "fiction",
163 "author": "Evelyn Waugh",
164 "title": "Sword of Honour",
165 "price": 12.99
166 },
167 {
168 "category": "fiction",
169 "author": "Herman Melville",
170 "title": "Moby Dick",
171 "isbn": "0-553-21311-3",
172 "price": 8.99
173 },
174 {
175 "category": "fiction",
176 "author": "J. R. R. Tolkien",
177 "title": "The Lord of the Rings",
178 "isbn": "0-395-19395-8",
179 "price": 22.99
180 }
181 ],
182 "bicycle": {
183 "color": "red",
184 "price": 19.95
185 }
186 },
187 "array":[0,1,2,3,4,5,6,7,8,9],
188 "orders":[
189 {
190 "ref":[1,2,3],
191 "id":1,
192 "filled": true
193 },
194 {
195 "ref":[4,5,6],
196 "id":2,
197 "filled": false
198 },
199 {
200 "ref":[7,8,9],
201 "id":3,
202 "filled": null
203 }
204 ],
205 "expensive": 10 }"#
206 }
207
208 #[test]
209 fn update_by_path_test() -> Queried<()> {
210 let mut json = json!([
211 {"verb": "RUN","distance":[1]},
212 {"verb": "TEST"},
213 {"verb": "DO NOT RUN"}
214 ]);
215
216 let path = json.query_only_path("$[?(@.verb == 'RUN')]")?;
217 let elem = path.first().cloned().unwrap_or_default();
218
219 if let Some(v) = json
220 .reference_mut(elem)
221 .and_then(|v| v.as_object_mut())
222 .and_then(|v| v.get_mut("distance"))
223 .and_then(|v| v.as_array_mut())
224 {
225 v.push(json!(2))
226 }
227
228 assert_eq!(
229 json,
230 json!([
231 {"verb": "RUN","distance":[1,2]},
232 {"verb": "TEST"},
233 {"verb": "DO NOT RUN"}
234 ])
235 );
236
237 Ok(())
238 }
239
240 #[test]
241 fn simple_test() {
242 let j1 = json!(2);
243 let _ = test("[1,2,3]", "$[1]", vec![(&j1, "$[1]".to_string())]);
244 }
245
246 #[test]
247 fn root_test() {
248 let js = serde_json::from_str(template_json()).unwrap();
249 let _ = test(template_json(), "$", vec![(&js, "$")]);
250 }
251
252 #[test]
253 fn descent_test() {
254 let v1 = json!("reference");
255 let v2 = json!("fiction");
256 let _ = test(
257 template_json(),
258 "$..category",
259 vec![
260 (&v1, "$['store']['book'][0]['category']"),
261 (&v2, "$['store']['book'][1]['category']"),
262 (&v2, "$['store']['book'][2]['category']"),
263 (&v2, "$['store']['book'][3]['category']"),
264 ],
265 );
266 let js1 = json!(19.95);
267 let js2 = json!(8.95);
268 let js3 = json!(12.99);
269 let js4 = json!(8.99);
270 let js5 = json!(22.99);
271 let _ = test(
272 template_json(),
273 "$.store..price",
274 vec![
275 (&js1, "$['store']['bicycle']['price']"),
276 (&js2, "$['store']['book'][0]['price']"),
277 (&js3, "$['store']['book'][1]['price']"),
278 (&js4, "$['store']['book'][2]['price']"),
279 (&js5, "$['store']['book'][3]['price']"),
280 ],
281 );
282 let js1 = json!("Nigel Rees");
283 let js2 = json!("Evelyn Waugh");
284 let js3 = json!("Herman Melville");
285 let js4 = json!("J. R. R. Tolkien");
286 let _ = test(
287 template_json(),
288 "$..author",
289 vec![
290 (&js1, "$['store']['book'][0]['author']"),
291 (&js2, "$['store']['book'][1]['author']"),
292 (&js3, "$['store']['book'][2]['author']"),
293 (&js4, "$['store']['book'][3]['author']"),
294 ],
295 );
296 }
297
298 #[test]
299 fn wildcard_test() {
300 let js1 = json!("reference");
301 let js2 = json!("fiction");
302 let _ = test(
303 template_json(),
304 "$..book.[*].category",
305 vec![
306 (&js1, "$['store']['book'][0].['category']"),
307 (&js2, "$['store']['book'][1].['category']"),
308 (&js2, "$['store']['book'][2].['category']"),
309 (&js2, "$['store']['book'][3].['category']"),
310 ],
311 );
312 let js1 = json!("Nigel Rees");
313 let js2 = json!("Evelyn Waugh");
314 let js3 = json!("Herman Melville");
315 let js4 = json!("J. R. R. Tolkien");
316 let _ = test(
317 template_json(),
318 "$.store.book[*].author",
319 vec![
320 (&js1, "$['store']['book'][0]['author']"),
321 (&js2, "$['store']['book'][1]['author']"),
322 (&js3, "$['store']['book'][2]['author']"),
323 (&js4, "$['store']['book'][3]['author']"),
324 ],
325 );
326 }
327
328 #[test]
329 fn descendent_wildcard_test() {
330 let js1 = json!("0-553-21311-3");
331 let js2 = json!("0-395-19395-8");
332 let _ = test(
333 template_json(),
334 "$..*.[?@].isbn",
335 vec![
336 (&js1, "$['store']['book'][2]['isbn']"),
337 (&js2, "$['store']['book'][3]['isbn']"),
338 ],
339 );
340 }
341
342 #[test]
343 fn field_test() {
344 let value = json!({"active":1});
345 let _ = test(
346 r#"{"field":{"field":[{"active":1},{"passive":1}]}}"#,
347 "$.field.field[?@.active]",
348 vec![(&value, "$['field']['field'][0]")],
349 );
350 }
351
352 #[test]
353 fn index_index_test() {
354 let value = json!("0-553-21311-3");
355 let _ = test(
356 template_json(),
357 "$..book[2].isbn",
358 vec![(&value, "$['store']['book'][2]['isbn']")],
359 );
360 }
361
362 #[test]
363 fn index_unit_index_test() {
364 let value = json!("0-553-21311-3");
365 let _ = test(
366 template_json(),
367 "$..book[2,4].isbn",
368 vec![(&value, "$['store']['book'][2]['isbn']")],
369 );
370 let value1 = json!("0-395-19395-8");
371 let _ = test(
372 template_json(),
373 "$..book[2,3].isbn",
374 vec![
375 (&value, "$['store']['book'][2]['isbn']"),
376 (&value1, "$['store']['book'][3]['isbn']"),
377 ],
378 );
379 }
380
381 #[test]
382 fn index_unit_keys_test() {
383 let js1 = json!("Moby Dick");
384 let js2 = json!(8.99);
385 let js3 = json!("The Lord of the Rings");
386 let js4 = json!(22.99);
387 let _ = test(
388 template_json(),
389 "$..book[2,3]['title','price']",
390 vec![
391 (&js1, "$['store']['book'][2]['title']"),
392 (&js3, "$['store']['book'][3]['title']"),
393 (&js2, "$['store']['book'][2]['price']"),
394 (&js4, "$['store']['book'][3]['price']"),
395 ],
396 );
397 }
398
399 #[test]
400 fn index_slice_test() -> Parsed<()> {
401 let i0 = "$['array'][0]";
402 let i1 = "$['array'][1]";
403 let i2 = "$['array'][2]";
404 let i3 = "$['array'][3]";
405 let i4 = "$['array'][4]";
406 let i5 = "$['array'][5]";
407 let i6 = "$['array'][6]";
408 let i7 = "$['array'][7]";
409 let i8 = "$['array'][8]";
410 let i9 = "$['array'][9]";
411
412 let j0 = json!(0);
413 let j1 = json!(1);
414 let j2 = json!(2);
415 let j3 = json!(3);
416 let j4 = json!(4);
417 let j5 = json!(5);
418 let j6 = json!(6);
419 let j7 = json!(7);
420 let j8 = json!(8);
421 let j9 = json!(9);
422 test(
423 template_json(),
424 "$.array[:]",
425 vec![
426 (&j0, i0),
427 (&j1, i1),
428 (&j2, i2),
429 (&j3, i3),
430 (&j4, i4),
431 (&j5, i5),
432 (&j6, i6),
433 (&j7, i7),
434 (&j8, i8),
435 (&j9, i9),
436 ],
437 )?;
438 test(
439 template_json(),
440 "$.array[1:4:2]",
441 vec![(&j1, i1), (&j3, i3)],
442 )?;
443 test(
444 template_json(),
445 "$.array[::3]",
446 vec![(&j0, i0), (&j3, i3), (&j6, i6), (&j9, i9)],
447 )?;
448 test(template_json(), "$.array[-1:]", vec![(&j9, i9)])?;
449 test(template_json(), "$.array[-2:-1]", vec![(&j8, i8)])?;
450
451 Ok(())
452 }
453
454 #[test]
455 fn index_filter_test() -> Parsed<()> {
456 let moby = json!("Moby Dick");
457 let rings = json!("The Lord of the Rings");
458 test(
459 template_json(),
460 "$..book[?@.isbn].title",
461 vec![
462 (&moby, "$['store']['book'][2]['title']"),
463 (&rings, "$['store']['book'][3]['title']"),
464 ],
465 )?;
466 let sword = json!("Sword of Honour");
467 test(
468 template_json(),
469 "$..book[?(@.price != 8.95)].title",
470 vec![
471 (&sword, "$['store']['book'][1]['title']"),
472 (&moby, "$['store']['book'][2]['title']"),
473 (&rings, "$['store']['book'][3]['title']"),
474 ],
475 )?;
476 let sayings = json!("Sayings of the Century");
477 test(
478 template_json(),
479 "$..book[?(@.price == 8.95)].title",
480 vec![(&sayings, "$['store']['book'][0]['title']")],
481 )?;
482
483 let js12 = json!(12.99);
484 let js899 = json!(8.99);
485 let js2299 = json!(22.99);
486 test(
487 template_json(),
488 "$..book[?@.price >= 8.99].price",
489 vec![
490 (&js12, "$['store']['book'][1]['price']"),
491 (&js899, "$['store']['book'][2]['price']"),
492 (&js2299, "$['store']['book'][3]['price']"),
493 ],
494 )?;
495
496 test(
497 template_json(),
498 "$..book[?(@.price >= $.expensive)].price",
499 vec![
500 (&js12, "$['store']['book'][1]['price']"),
501 (&js2299, "$['store']['book'][3]['price']"),
502 ],
503 )?;
504 Ok(())
505 }
506
507 #[test]
508 fn union_quotes() -> Queried<()> {
509 let json = json!({
510 "a": "ab",
511 "b": "bc"
512 });
513
514 let vec = js_path("$['a',\r'b']", &json)?;
515
516 assert_eq!(
517 vec,
518 vec![
519 (&json!("ab"), "$['a']".to_string()).into(),
520 (&json!("bc"), "$['b']".to_string()).into(),
521 ]
522 );
523
524 Ok(())
525 }
526
527 #[test]
528 fn space_between_selectors() -> Queried<()> {
529 let json = json!({
530 "a": {
531 "b": "ab"
532 }
533 });
534
535 let vec = js_path("$['a'] \r['b']", &json)?;
536
537 assert_eq!(vec, vec![(&json!("ab"), "$['a']['b']".to_string()).into(),]);
538
539 Ok(())
540 }
541 #[test]
542 fn space_in_search() -> Queried<()> {
543 let json = json!(["foo", "123"]);
544
545 let vec = js_path("$[?search(@\n,'[a-z]+')]", &json)?;
546
547 assert_eq!(vec, vec![(&json!("foo"), "$[0]".to_string()).into(),]);
548
549 Ok(())
550 }
551 #[test]
552 fn filter_key() -> Queried<()> {
553 let json = json!([
554 {
555 "a": "b",
556 "d": "e"
557 },
558 {
559 "a": 1,
560 "d": "f"
561 }
562 ]);
563
564 let vec = js_path("$[?@.a!=\"b\"]", &json)?;
565
566 assert_eq!(
567 vec,
568 vec![(&json!({"a":1, "d":"f"}), "$[1]".to_string()).into(),]
569 );
570
571 Ok(())
572 }
573
574 #[test]
575 fn regex_key() -> Queried<()> {
576 let json = json!({
577 "regex": "b.?b",
578 "values": [
579 "abc",
580 "bcd",
581 "bab",
582 "bba",
583 "bbab",
584 "b",
585 true,
586 [],
587 {}
588 ]
589 });
590
591 let vec = js_path("$.values[?match(@, $.regex)]", &json)?;
592
593 assert_eq!(
594 vec,
595 vec![(&json!("bab"), "$['values'][2]".to_string()).into(),]
596 );
597
598 Ok(())
599 }
600 #[test]
601 fn name_sel() -> Queried<()> {
602 let json = json!({
603 "/": "A"
604 });
605
606 let vec = js_path("$['\\/']", &json)?;
607
608 assert_eq!(vec, vec![(&json!("A"), "$['/']".to_string()).into(),]);
609
610 Ok(())
611 }
612 #[test]
613 fn unicode_fns() -> Queried<()> {
614 let json = json!(["ж", "Ж", "1", "жЖ", true, [], {}]);
615
616 let vec = js_path("$[?match(@, '\\\\p{Lu}')]", &json)?;
617
618 assert_eq!(vec, vec![(&json!("Ж"), "$[1]".to_string()).into(),]);
619
620 Ok(())
621 }
622 #[test]
623 fn fn_res_can_not_compare() -> Queried<()> {
624 let json = json!({});
625
626 let vec = js_path("$[?match(@.a, 'a.*')==true]", &json);
627
628 assert!(vec.is_err());
629
630 Ok(())
631 }
632 #[test]
633 fn too_small() -> Queried<()> {
634 let json = json!({});
635
636 let vec = js_path("$[-9007199254740992]", &json);
637
638 assert!(vec.is_err());
639
640 Ok(())
641 }
642 #[test]
643 fn filter_data() -> Queried<()> {
644 let json = json!({
645 "a": 1,
646 "b": 2,
647 "c": 3
648 });
649
650 let vec: Vec<String> = json.query_only_path("$[?@<3]")?.into_iter().collect();
651
652 assert_eq!(vec, vec!["$['a']".to_string(), "$['b']".to_string()]);
653
654 Ok(())
655 }
656 #[test]
657 fn exp_no_error() -> Queried<()> {
658 let json = json!([
659 {
660 "a": 100,
661 "d": "e"
662 },
663 {
664 "a": 100.1,
665 "d": "f"
666 },
667 {
668 "a": "100",
669 "d": "g"
670 }
671 ]);
672
673 let vec: Vec<&Value> = json.query("$[?@.a==1E2]")?;
674 assert_eq!(vec, vec![&json!({"a":100, "d":"e"})]);
675
676 Ok(())
677 }
678 #[test]
679 fn single_quote() -> Queried<()> {
680 let json = json!({
681 "a'": "A",
682 "b": "B"
683 });
684
685 let vec = js_path("$[\"a'\"]", &json)?;
686 assert_eq!(vec, vec![(&json!("A"), "$['a\\'']".to_string()).into(),]);
687
688 Ok(())
689 }
690 #[test]
691 fn union() -> Queried<()> {
692 let json = json!([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
693
694 let vec: Vec<QueryRef<Value>> = json.query_with_path("$[1,5:7]")?;
695 assert_eq!(
696 vec,
697 vec![
698 (&json!(1), "$[1]".to_string()).into(),
699 (&json!(5), "$[5]".to_string()).into(),
700 (&json!(6), "$[6]".to_string()).into(),
701 ]
702 );
703
704 Ok(())
705 }
706
707 #[test]
708 fn basic_descendent() -> Queried<()> {
709 let json = json!({
710 "o": [
711 0,
712 1,
713 [
714 2,
715 3
716 ]
717 ]
718 });
719
720 let vec = js_path("$..[1]", &json)?;
721 assert_eq!(
722 vec,
723 vec![
724 (&json!(1), "$['o'][1]".to_string()).into(),
725 (&json!(3), "$['o'][2][1]".to_string()).into(),
726 ]
727 );
728
729 Ok(())
730 }
731 #[test]
732 fn filter_absent() -> Queried<()> {
733 let json = json!([
734 {
735 "list": [
736 1
737 ]
738 }
739 ]);
740
741 let vec = js_path("$[?@.absent==@.list[9]]", &json)?;
742 assert_eq!(
743 vec,
744 vec![(&json!({"list": [1]}), "$[0]".to_string()).into(),]
745 );
746
747 Ok(())
748 }
749
750 #[test]
751 fn filter_star() -> Queried<()> {
752 let json = json!([1,[],[2],{},{"a": 3}]);
753
754 let vec = json.query_with_path("$[?@.*]")?;
755 assert_eq!(
756 vec,
757 vec![
758 (&json!([2]), "$[2]".to_string()).into(),
759 (&json!({"a": 3}), "$[4]".to_string()).into(),
760 ]
761 );
762
763 Ok(())
764 }
765
766 #[test]
767 fn space_test() -> Queried<()> {
768 let json = json!({ " ": "A"});
769
770 let vec = json.query_with_path("$[' ']")?;
771 assert_eq!(vec, vec![(&json!("A"), "$[\' \']".to_string()).into(),]);
772
773 Ok(())
774 }
775 #[test]
776 fn neg_idx() -> Queried<()> {
777 let json = json!(["first", "second"]);
778
779 let vec = json.query_with_path("$[-2]")?;
780 assert_eq!(vec, vec![(&json!("first"), "$[0]".to_string()).into(),]);
781
782 Ok(())
783 }
784
785 #[test]
786 fn filter_slice() -> Queried<()> {
787 let json = json!([
788 1,
789 [],
790 [
791 2
792 ],
793 [
794 2,
795 3,
796 4
797 ],
798 {},
799 {
800 "a": 3
801 }
802 ]);
803
804 let vec = json.query_with_path("$[?@[0:2]]")?;
805 assert_eq!(
806 vec,
807 vec![
808 (&json!([2]), "$[2]").into(),
809 (&json!([2, 3, 4]), "$[3]").into(),
810 ]
811 );
812
813 Ok(())
814 }
815
816 #[test]
817 fn surr_pairs() -> Queried<()> {
818 let json = json!({
819 "𝄞": "A"
820 });
821 let vec = json.query_with_path("$['𝄞']")?;
822 assert_eq!(vec, vec![(&json!("A"), "$['𝄞']".to_string()).into()]);
823
824 Ok(())
825 }
826 #[test]
827 fn tab_key() -> Queried<()> {
828 let json = json!({
829 "\t": "A"
830 });
831 let vec = json.query_with_path("$['\\t']")?;
832 assert_eq!(vec, vec![(&json!("A"), "$['\\t']".to_string()).into()]);
833
834 Ok(())
835 }
836 #[test]
837 fn escaped_up_hex() -> Queried<()> {
838 let json = json!({
839 "☺": "A"
840 });
841 let vec = json.query_with_path("$['☺']")?;
842 assert_eq!(vec, vec![(&json!("A"), "$['☺']".to_string()).into()]);
843
844 Ok(())
845 }
846 #[test]
847 fn carr_return() -> Queried<()> {
848 let json = json!({
849 "\r": "A"
850 });
851 let vec = json.query_with_path("$['\\r']")?;
852 assert_eq!(vec, vec![(&json!("A"), "$['\\r']".to_string()).into()]);
853
854 Ok(())
855 }
856
857 #[test]
859 fn escaped_name_selectors() -> Queried<()> {
860 let escapes = [
861 ("\\b", "\u{0008}"),
862 ("\\f", "\u{000C}"),
863 ("\\n", "\n"),
864 ("\\r", "\r"),
865 ("\\t", "\t"),
866 ("\\/", "/"),
867 ("\\\\", "\\"),
868 ("\\u263A", "\u{263A}"),
869 ("\\u263a", "\u{263A}"),
870 ("\\uD834\\uDD1E", "\u{1D11E}"),
871 ("\\ud83d\\ude00", "\u{1F600}"),
872 ("\\uD7FF", "\u{D7FF}"),
873 ("\\uE000", "\u{E000}"),
874 ("\\u0000", "\u{0000}"),
875 ("\\u001b", "\u{001B}"),
876 ];
877 for (escaped, name) in escapes {
878 let json = json!({ name: "A" });
879 for selector in [format!("$[\"{}\"]", escaped), format!("$['{}']", escaped)] {
880 let found: Vec<&Value> = json.query(&selector)?;
881 assert_eq!(found, vec![&json!("A")], "{}", selector);
882 }
883 }
884
885 assert_eq!(json!({"\"": "A"}).query("$[\"\\\"\"]")?, vec![&json!("A")]);
887 assert_eq!(json!({"'": "A"}).query("$['\\'']")?, vec![&json!("A")]);
888 assert_eq!(
889 json!({"'a'": "A"}).query("$['\\'a\\'']")?,
890 vec![&json!("A")]
891 );
892 assert_eq!(json!({"a\"b": "A"}).query("$['a\"b']")?, vec![&json!("A")]);
893
894 assert!(parse_json_path("$[\"\\uD800\"]").is_err());
896 assert!(parse_json_path("$[\"\\uDC00\"]").is_err());
897 assert!(parse_json_path("$[\"\\uD800\\uD800\"]").is_err());
898
899 Ok(())
900 }
901
902 #[test]
904 fn escaped_string_literals() -> Queried<()> {
905 let json = json!(["quoted' literal", "quoted\\' literal", "a\tb", "a\\tb"]);
906
907 assert_eq!(
908 json.query("$[?@ == 'quoted\\' literal']")?,
909 vec![&json!("quoted' literal")]
910 );
911 assert_eq!(json.query("$[?@ == \"a\\tb\"]")?, vec![&json!("a\tb")]);
912 assert_eq!(json.query("$[?@ == 'a\\\\tb']")?, vec![&json!("a\\tb")]);
913
914 Ok(())
915 }
916
917 #[test]
919 fn regex_argument_is_the_literal_value() -> Queried<()> {
920 let json = json!(["a.c", "a\\bc", "abc"]);
922 assert_eq!(
923 json.query("$[?match(@, 'a\\\\\\\\.c')]")?,
924 vec![&json!("a\\bc")]
925 );
926
927 let json = json!(["a/b", "ab"]);
929 assert_eq!(json.query("$[?match(@, 'a\\/b')]")?, vec![&json!("a/b")]);
930
931 let json = json!(["\"x\"", "yxy"]);
933 assert_eq!(json.query("$[?search(@, '\"x\"')]")?, vec![&json!("\"x\"")]);
934
935 Ok(())
936 }
937
938 #[test]
940 fn regex_dot_does_not_match_line_breaks() -> Queried<()> {
941 let json = json!(["a", "\r", "\n", "\u{2028}", "\r\n", "x\ry"]);
942 assert_eq!(
943 json.query("$[?match(@, '.')]")?,
944 vec![&json!("a"), &json!("\u{2028}")]
945 );
946 assert_eq!(
947 json.query("$[?search(@, '.')]")?,
948 vec![&json!("a"), &json!("\u{2028}"), &json!("x\ry")]
949 );
950 assert_eq!(
951 json.query("$[?match(@, 'x[.\\r]y')]")?,
952 vec![&json!("x\ry")]
953 );
954 assert_eq!(json.query("$[?match(@, 'x\\\\.y')]")?, Vec::<&Value>::new());
955
956 Ok(())
957 }
958
959 #[test]
961 fn regex_match_anchors_alternation() -> Queried<()> {
962 let json = json!(["a", "b", "ab", "xb", "ax"]);
963 assert_eq!(
964 json.query("$[?match(@, 'a|b')]")?,
965 vec![&json!("a"), &json!("b")]
966 );
967 assert_eq!(
968 json.query("$[?search(@, 'a|b')]")?,
969 vec![
970 &json!("a"),
971 &json!("b"),
972 &json!("ab"),
973 &json!("xb"),
974 &json!("ax")
975 ]
976 );
977
978 Ok(())
979 }
980
981 #[test]
983 fn regex_with_context() -> Queried<()> {
984 fn select<'a>(
985 path: &str,
986 json: &'a Value,
987 ctx: &mut JsonPathEvalContext,
988 ) -> Queried<Vec<&'a Value>> {
989 let found = parse_json_path(path)?.execute_with_context(json, ctx)?;
990 assert_eq!(found, json.query_with_path(path)?);
991 Ok(found.into_iter().map(QueryRef::val).collect())
992 }
993
994 let mut ctx = JsonPathEvalContext::with_regex_cache();
996
997 let items = json!([
998 {"name": "widget-7", "sku": "SKU-000017"},
999 {"name": "widget-17", "sku": "SKU-000020"},
1000 {"name": "gadget-7", "sku": "SKU-000011"}
1001 ]);
1002 assert_eq!(
1003 select(
1004 "$[?match(@.name, 'widget-[0-9]*7') && search(@.sku, '0{3}1')]",
1005 &items,
1006 &mut ctx
1007 )?,
1008 vec![&items[0]]
1009 );
1010 assert_eq!(
1012 select("$[?search(@.sku, @.name)]", &items, &mut ctx)?,
1013 Vec::<&Value>::new()
1014 );
1015
1016 let names = json!(["a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10"]);
1017 let filter = (0..10)
1019 .map(|i| format!("match(@, 'a{i}')"))
1020 .collect::<Vec<_>>()
1021 .join(" || ");
1022 assert_eq!(
1023 select(&format!("$[?{filter}]"), &names, &mut ctx)?,
1024 (0..10).map(|i| &names[i]).collect::<Vec<_>>()
1025 );
1026 assert_eq!(
1028 select("$[?match(@, 'a1')]", &names, &mut ctx)?,
1029 vec![&names[1]]
1030 );
1031 assert_eq!(
1032 select("$[?search(@, 'a1')]", &names, &mut ctx)?,
1033 vec![&names[1], &names[10]]
1034 );
1035 assert_eq!(
1037 select("$[?match(@, 'a[')]", &names, &mut ctx)?,
1038 Vec::<&Value>::new()
1039 );
1040
1041 Ok(())
1042 }
1043
1044 #[test]
1046 fn normalized_paths_round_trip() -> Queried<()> {
1047 let names = [
1048 "a",
1049 "",
1050 " ",
1051 "'",
1052 "\"",
1053 "\\",
1054 "\\'",
1055 "/",
1056 "~",
1057 "a/b",
1058 "a~b",
1059 "~0",
1060 "'a'",
1061 "\"a\"",
1062 "\u{0008}",
1063 "\u{000C}",
1064 "\n",
1065 "\r",
1066 "\t",
1067 "\u{0000}",
1068 "\u{000B}",
1069 "\u{001F}",
1070 "\u{007F}",
1071 "\u{263A}",
1072 "\u{1F600}",
1073 ];
1074 for name in names {
1075 let json = json!({ name: "A" });
1076
1077 let paths = json.query_only_path("$[*]")?;
1078 assert_eq!(paths.len(), 1, "{:?}", name);
1079
1080 let found: Vec<&Value> = json.query(&paths[0])?;
1081 assert_eq!(found, vec![&json!("A")], "{:?} -> {}", name, paths[0]);
1082 assert_eq!(json.reference(&paths[0]), Some(&json!("A")), "{}", paths[0]);
1083 }
1084
1085 assert_eq!(
1087 json!({"'\\\t\u{000B}/": "A"}).query_only_path("$[*]")?,
1088 vec!["$['\\'\\\\\\t\\u000b/']".to_string()]
1089 );
1090
1091 Ok(())
1092 }
1093
1094 #[test]
1095 fn delete_by_path_with_slash_in_name() -> Queried<()> {
1096 let mut json = json!({"a/b": {"c": 1, "d": 2}});
1097
1098 assert_eq!(json.delete_by_path("$['a/b']['c']")?, 1);
1099 assert_eq!(json, json!({"a/b": {"d": 2}}));
1100
1101 Ok(())
1102 }
1103
1104 #[test]
1105 fn prepared_query() -> Queried<()> {
1106 let json1 = json!({
1107 "a": 1,
1108 "b": 2,
1109 "c": 3
1110 });
1111 let json2 = json!({
1112 "a": 1,
1113 "b": 2,
1114 "c": 3
1115 });
1116
1117 let jq = parse_json_path("$[?@<3]")?;
1118
1119 let v1 = js_path_process(&jq, &json1)?;
1120 let v2 = js_path_process(&jq, &json2)?;
1121
1122 assert_eq!(v1, v2);
1123
1124 Ok(())
1125 }
1126}