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
use serde_json::{value::Index, Value};

use super::{IndexMap, ValueType};

#[derive(Debug, Clone, PartialEq)]
pub struct ValuePath<'a> {
    pub value: &'a Value,
    pub path: Vec<String>, // TODO: Switch to Vec<Index> ?
}

impl<'a> ValuePath<'a> {
    pub fn new(value: &'a Value, path: Option<Vec<String>>) -> Self {
        let path = path.unwrap_or_default();
        ValuePath { value, path }
    }

    pub fn jsonpath(&self) -> String {
        let mut jsonpath = String::from("$");
        for part in &self.path {
            if part.starts_with('[') {
                jsonpath.push_str(part);
            } else {
                jsonpath.push('.');
                jsonpath.push_str(part);
            }
        }
        jsonpath
    }

    pub fn index(&self, index: impl JSONPathIndex) -> ValuePath<'a> {
        let mut child_path = self.path.to_vec();
        child_path.push(index.jsonpath());
        ValuePath {
            value: &self.value[index],
            path: child_path,
        }
    }
}

pub trait JSONPathIndex: Index {
    fn jsonpath(&self) -> String;
}

impl JSONPathIndex for usize {
    fn jsonpath(&self) -> String {
        format!("[{}]", self)
    }
}

impl JSONPathIndex for str {
    fn jsonpath(&self) -> String {
        self.to_string()
    }
}

impl JSONPathIndex for String {
    fn jsonpath(&self) -> String {
        self.to_string()
    }
}

impl<'a, T> JSONPathIndex for &'a T
where
    T: ?Sized + JSONPathIndex,
{
    fn jsonpath(&self) -> String {
        (**self).jsonpath()
    }
}

pub fn parse_value_paths(json: &Value, explode_array: bool) -> Vec<ValuePath> {
    let base_valuepath = ValuePath::new(json, None);
    _parse_value_paths(base_valuepath, explode_array)
}

fn _parse_value_paths(valuepath: ValuePath, explode_array: bool) -> Vec<ValuePath> {
    let mut paths = Vec::new();

    match valuepath.value {
        Value::Object(map) => {
            for (k, _) in map {
                let vp = valuepath.index(k);
                let inner_paths = _parse_value_paths(vp, explode_array);
                paths.extend(inner_paths)
            }
        }
        Value::Array(array) => {
            if explode_array {
                for (i, _array_value) in array.iter().enumerate() {
                    let vp = valuepath.index(i);
                    let inner_paths = _parse_value_paths(vp, explode_array);
                    paths.extend(inner_paths)
                }
            } else {
                paths.push(valuepath)
            }
        }
        Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => paths.push(valuepath),
    }
    paths
}

// impl<'a, I> std::ops::Index<I> for ValuePath<'a>
// where I: JSONPathIndex {
//     type Output = ValuePath<'a>;
//     fn index(&self, index: I) -> &Self::Output {
//         let mut child_path = self.path.clone();
//         child_path.push(index.jsonpath());
//         &ValuePath { value: &self.value[index], path: child_path }
//     }
// }

pub fn parse_json_paths(json: &Value) -> Vec<String> {
    json.value_paths(false)
        .into_iter()
        .map(|value_path| value_path.jsonpath())
        .collect()
}

pub fn parse_json_paths_types(json: &Value) -> IndexMap<String, String> {
    json.value_paths(false)
        .into_iter()
        .map(|value_path| (value_path.jsonpath(), value_path.value.value_type()))
        .collect()
}

pub trait ValuePaths {
    fn value_paths(&self, explode_array: bool) -> Vec<ValuePath>;
}

impl ValuePaths for Value {
    fn value_paths(&self, explode_array: bool) -> Vec<ValuePath> {
        parse_value_paths(self, explode_array)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use serde_json::json;

    #[test]
    fn basic_valuepath() {
        let v = json!({"key1": "value1", "key2": {"subkey1": "value1"}});
        let vp_0 = ValuePath::new(&v, None);
        assert_eq!(vp_0.jsonpath(), "$".to_string());

        let v_1 = &v["key2"];
        let vp_1 = vp_0.index("key2");
        assert_eq!(vp_1.value, v_1);
        assert_eq!(vp_1.path, vec!["key2".to_string()]);
        assert_eq!(vp_1.jsonpath(), "$.key2".to_string());
    }

    #[test]
    fn basic_valuepath_array() {
        let v = json!({"key1": "value1", "key2": ["a", "b"]});
        let vp_0 = ValuePath::new(&v, None);

        let v_2 = &v["key2"][0];
        let vp_1 = vp_0.index("key2");
        let vp_2 = vp_1.index(0);

        assert_eq!(vp_2.value, v_2);
        assert_eq!(vp_2.path, vec!["key2".to_string(), "[0]".to_string()]);
        assert_eq!(vp_1.jsonpath(), "$.key2".to_string());
        assert_eq!(vp_2.jsonpath(), "$.key2[0]".to_string())
    }

    #[test]
    fn parse_valuepaths() {
        let v = json!({"key1": "value1", "key2": ["a", "b"]});
        let vps = parse_value_paths(&v, false);

        let vp_0 = ValuePath::new(&v, None);
        let vp_1 = ValuePath::new(&v["key1"], Some(vec!["key1".to_string()]));
        let vp_2 = ValuePath::new(&v["key2"], Some(vec!["key2".to_string()]));
        let vp_1_alt = vp_0.index("key1");
        let vp_2_alt = vp_0.index("key2");

        let expected = vec![vp_1, vp_2];
        let expected_alt = vec![vp_1_alt, vp_2_alt];

        assert_eq!(vps, expected);
        assert_eq!(vps, expected_alt);
        assert_eq!(v.value_paths(false), expected);
        assert_eq!(v.value_paths(false), expected_alt);
    }

    #[test]
    fn parse_valuepaths_explode_array() {
        let v = json!({"key1": "value1", "key2": ["a", "b"]});
        let vps = parse_value_paths(&v, true);

        let vp_0 = ValuePath::new(&v, None);
        let vp_1 = ValuePath::new(&v["key1"], Some(vec!["key1".to_string()]));
        let vp_2_1 = ValuePath::new(
            &v["key2"][0],
            Some(vec!["key2".to_string(), "[0]".to_string()]),
        );
        let vp_2_2 = ValuePath::new(
            &v["key2"][1],
            Some(vec!["key2".to_string(), "[1]".to_string()]),
        );
        let vp_1_alt = vp_0.index("key1");
        let vp_2_1_alt = vp_0.index("key2").index(0);
        let vp_2_2_alt = vp_0.index("key2").index(1);

        assert_eq!(vps, vec![vp_1, vp_2_1, vp_2_2]);
        assert_eq!(vps, vec![vp_1_alt, vp_2_1_alt, vp_2_2_alt]);
    }

    #[test]
    fn typical_parse_json_paths() {
        let v = json!({"key1": "value1", "key2": {"subkey1": "value1"}});
        let out_expected = vec![String::from("$.key1"), String::from("$.key2.subkey1")];
        assert_eq!(parse_json_paths(&v), out_expected);
    }

    #[test]
    fn trivial_parse_json_paths() {
        let v = json!(1);
        let out_expected = vec![String::from("$")];
        assert_eq!(parse_json_paths(&v), out_expected);
    }

    #[test]
    fn typical_parse_json_paths_types() {
        let v = json!({"key1": "value1", "key2": {"subkey1": ["value1"]}});
        let mut out_expected = IndexMap::new();
        out_expected.insert("$.key1".to_string(), "String".to_string());
        out_expected.insert("$.key2.subkey1".to_string(), "Array".to_string());
        assert_eq!(parse_json_paths_types(&v), out_expected);
    }

    #[test]
    fn trivial_parse_json_paths_types() {
        let v = json!(1);
        let mut out_expected = IndexMap::new();
        out_expected.insert("$".to_string(), "Number".to_string());
        assert_eq!(parse_json_paths_types(&v), out_expected);
    }
}