Skip to main content

jsonpath_rust/query/
filter.rs

1use crate::parser::model::Filter;
2use crate::query::context::JsonPathEvalContext;
3use crate::query::queryable::Queryable;
4use crate::query::state::{Data, Pointer, State};
5use crate::query::Query;
6
7impl Query for Filter {
8    fn process_with_context<'a, T: Queryable>(
9        &self,
10        state: State<'a, T>,
11        ctx: &mut JsonPathEvalContext,
12    ) -> State<'a, T> {
13        let root = state.root;
14        state.flat_map(|p| {
15            if p.is_internal() {
16                Data::Value(self.filter_item(p, root, ctx).into())
17            } else if let Some(items) = p.inner.as_array() {
18                Data::Refs(
19                    items
20                        .into_iter()
21                        .enumerate()
22                        .filter(|(_, item)| self.filter_item(Pointer::empty(*item), root, ctx))
23                        .map(|(idx, item)| Pointer::idx(item, p.path.clone(), idx))
24                        .collect(),
25                )
26            } else if let Some(items) = p.inner.as_object() {
27                Data::Refs(
28                    items
29                        .into_iter()
30                        .filter(|(_, item)| self.filter_item(Pointer::empty(*item), root, ctx))
31                        .map(|(key, item)| Pointer::key(item, p.path.clone(), key))
32                        .collect(),
33                )
34            } else {
35                return Data::Nothing;
36            }
37        })
38    }
39}
40
41impl Filter {
42    fn process_elem<'a, T: Queryable>(
43        &self,
44        state: State<'a, T>,
45        ctx: &mut JsonPathEvalContext,
46    ) -> State<'a, T> {
47        let process_cond = |filter: &Filter| {
48            filter
49                .process_with_context(state.clone(), ctx)
50                .ok_val()
51                .and_then(|v| v.as_bool())
52                .unwrap_or_default()
53        };
54        match self {
55            Filter::Or(ors) => State::bool(ors.iter().any(process_cond), state.root),
56            Filter::And(ands) => State::bool(ands.iter().all(process_cond), state.root),
57            Filter::Atom(atom) => atom.process_with_context(state, ctx),
58        }
59    }
60
61    fn filter_item<'a, T: Queryable>(
62        &self,
63        item: Pointer<'a, T>,
64        root: &T,
65        ctx: &mut JsonPathEvalContext,
66    ) -> bool {
67        self.process_elem(State::data(root, Data::Ref(item.clone())), ctx)
68            .ok_val()
69            .and_then(|v| v.as_bool())
70            .unwrap_or_default()
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use crate::query::js_path;
77    use serde_json::json;
78
79    #[test]
80    fn smoke_ok() {
81        let json = json!({"a" : [1,2,3]});
82
83        assert_eq!(
84            js_path("$.a[? @ > 1]", &json),
85            Ok(vec![
86                (&json!(2), "$['a'][1]".to_string()).into(),
87                (&json!(3), "$['a'][2]".to_string()).into(),
88            ])
89        );
90    }
91
92    #[test]
93    fn existence() {
94        let json = json!({
95          "a": {
96            "a":{"b":1},
97            "c": {
98              "b": 2
99            },
100            "d": {
101              "b1": 3
102            }
103          }
104        });
105        assert_eq!(
106            js_path("$.a[?@.b]", &json),
107            Ok(vec![
108                (&json!({"b":1}), "$['a']['a']".to_string()).into(),
109                (&json!({"b":2}), "$['a']['c']".to_string()).into(),
110            ])
111        );
112    }
113
114    #[test]
115    fn existence_of_empty_containers() {
116        let json = json!({
117          "a": {
118            "empty_array": {"b": []},
119            "empty_object": {"b": {}},
120            "empty_string": {"b": ""},
121            "no_b": {"c": 1}
122          }
123        });
124        // RFC 9535 2.3.5.2: a test expression is true when the nodelist it
125        // produces is non-empty, whatever the value of the nodes.
126        assert_eq!(
127            js_path("$.a[?@.b]", &json),
128            Ok(vec![
129                (&json!({"b": []}), "$['a']['empty_array']".to_string()).into(),
130                (&json!({"b": {}}), "$['a']['empty_object']".to_string()).into(),
131                (&json!({"b": ""}), "$['a']['empty_string']".to_string()).into(),
132            ])
133        );
134    }
135
136    #[test]
137    fn existence_or() {
138        let json = json!({
139          "a": {
140            "a":{"b":1},
141            "c": {
142              "b": 2
143            },
144            "d": {
145              "b1": 3
146            },
147            "e": {
148              "b2": 3
149            }
150          }
151        });
152        assert_eq!(
153            js_path("$.a[?@.b || @.b1]", &json),
154            Ok(vec![
155                (&json!({"b":1}), "$['a']['a']".to_string()).into(),
156                (&json!({"b":2}), "$['a']['c']".to_string()).into(),
157                (&json!({"b1":3}), "$['a']['d']".to_string()).into(),
158            ])
159        );
160    }
161}