Skip to main content

jsonpath_rust/query/
jp_query.rs

1use crate::parser::model::{JpQuery, Segment};
2use crate::query::context::JsonPathEvalContext;
3use crate::query::queryable::Queryable;
4use crate::query::state::State;
5use crate::query::Query;
6
7impl Query for JpQuery {
8    fn process_with_context<'a, T: Queryable>(
9        &self,
10        state: State<'a, T>,
11        ctx: &mut JsonPathEvalContext,
12    ) -> State<'a, T> {
13        self.segments.process_with_context(state, ctx)
14    }
15}
16
17impl Query for Vec<Segment> {
18    fn process_with_context<'a, T: Queryable>(
19        &self,
20        state: State<'a, T>,
21        ctx: &mut JsonPathEvalContext,
22    ) -> State<'a, T> {
23        self.iter().fold(state, |next, segment| {
24            segment.process_with_context(next, ctx)
25        })
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use crate::parser::model::{JpQuery, Segment, Selector};
32    use crate::query::state::{Data, Pointer, State};
33    use crate::query::Query;
34    use serde_json::json;
35
36    #[test]
37    fn test_process() {
38        let value = json!({
39          "result": [
40            {
41              "message": "Hello, Emmy! Your order number is: #100",
42              "phoneNumber": "255-301-9429",
43              "phoneVariation": "+90 398 588 10 73",
44              "status": "active",
45              "name": {
46                "first": "Blaise",
47                "middle": "Kyle",
48                "last": "Fadel"
49              }
50            }
51          ]
52        });
53
54        let query = JpQuery::new(vec![
55            Segment::Selector(Selector::Name("result".to_string())),
56            Segment::Selector(Selector::Index(0)),
57            Segment::Selector(Selector::Name("name".to_string())),
58            Segment::Selector(Selector::Name("first".to_string())),
59        ]);
60
61        let state = State::data(&value, Data::new_ref(Pointer::new(&value, "$".to_string())));
62
63        let result = query.process(state);
64        assert_eq!(
65            result.ok_ref(),
66            Some(vec![Pointer::new(
67                &json!("Blaise"),
68                "$['result'][0]['name']['first']".to_string()
69            )])
70        );
71    }
72}