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
use crate::style::{PresetStyle, Style};
use serde_json::Value;
use std::collections::VecDeque;

/// Single element struct containing the path, set of array indices, and json value
#[derive(Debug, PartialEq)]
pub struct Element<'a> {
    /// The full path from the base of a json structure to the value contained in the `Element`
    pub path: String,
    /// The full set of _array_ indices in the path, useful for grouping sets of `Element` structs to the same array element
    pub indices: Vec<usize>,
    /// The `serde_json::Value` of described by the path
    pub value: &'a Value,
}

/// Iteration strict containing a queue of elements that still need to be yielded along with a style object
#[derive(Debug)]
pub struct Iter<'a> {
    style: Style<'a>,
    items: VecDeque<Element<'a>>,
}

/// Named `Iter` internally, but `Iterator` externally
impl<'a> Iter<'a> {
    /// Create a new json keypath iterator
    ///
    /// Example:
    /// ```rust
    /// use serde_json::json;
    /// use json_keypath_iter::{Iterator, Element};
    ///
    /// let value = json!({"a": [1, 2]});
    /// let iter = Iterator::new(&value);
    /// let items: Vec<_> = iter.collect();
    ///
    /// assert_eq!(items[0], Element { path: "[\"a\"][0]".into(), indices: vec![0], value: &json!(1), });
    /// assert_eq!(items[1], Element { path: "[\"a\"][1]".into(), indices: vec![1], value: &json!(2), });
    /// ```
    pub fn new(json: &'a Value) -> Self {
        let mut queue = VecDeque::new();
        queue.push_back(Element {
            path: String::from(""),
            indices: Vec::new(),
            value: json,
        });

        Self {
            items: queue,
            style: PresetStyle::SquareBrackets.into(),
        }
    }

    /// Optionally used to set a custom style for the path in elements
    ///
    /// Example:
    /// ```rust
    /// use serde_json::json;
    /// use json_keypath_iter::{Style, PresetStyle, Iterator, Element};
    ///
    /// let style: Style = PresetStyle::CommonJs.into();
    /// let value = json!({"x42": [true, [null, "Hello there."]]});
    /// let iter = Iterator::new(&value).use_style(style);
    /// let items: Vec<_> = iter.collect();
    ///
    /// assert_eq!(items[0], Element { path: ".x42[0]".into(), indices: vec![0], value: &json!(true), });
    /// assert_eq!(items[1], Element { path: ".x42[1][0]".into(), indices: vec![1, 0], value: &json!(null), });
    /// assert_eq!(items[2], Element { path: ".x42[1][1]".into(), indices: vec![1, 1], value: &json!("Hello there."), });
    /// ```
    pub fn use_style(mut self, style: Style<'a>) -> Self {
        self.style = style;
        self
    }
}

impl<'a> From<&'a Value> for Iter<'a> {
    fn from(item: &'a Value) -> Iter<'a> {
        Iter::new(item)
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = Element<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        'items: while let Some(el) = self.items.pop_front() {
            match el.value {
                Value::Object(obj) => {
                    for (key, val) in obj.iter().rev() {
                        self.items.push_front(Element {
                            path: self.style.object_format(&el.path, key),
                            indices: el.indices.clone(),
                            value: val,
                        });
                    }

                    match self.style.should_skip_object_parents() {
                        true => continue 'items,
                        false => return Some(el),
                    };
                }
                Value::Array(arr) => {
                    for (index, val) in arr.iter().enumerate().rev() {
                        let mut indices_vec = el.indices.to_vec();
                        indices_vec.push(index);

                        self.items.push_front(Element {
                            path: self.style.array_format(&el.path, index),
                            indices: indices_vec,
                            value: val,
                        });
                    }

                    match self.style.should_skip_array_parents() {
                        true => continue 'items,
                        false => return Some(el),
                    };
                }
                _ => return Some(el),
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::style::StyleBuilder;
    use serde_json::json;

    #[test]
    fn null_to_iter() {
        let value = json!(null);
        let items: Vec<_> = Iter::new(&value).collect();

        assert_eq!(items.len(), 1);
        assert_eq!(
            items[0],
            Element {
                path: String::from(""),
                indices: Vec::new(),
                value: &Value::Null,
            }
        );
    }

    #[test]
    fn bool_to_iter() {
        let value = json!(true);
        let items: Vec<_> = Iter::new(&value).collect();

        assert_eq!(items.len(), 1);
        assert_eq!(
            items[0],
            Element {
                path: String::from(""),
                indices: Vec::new(),
                value: &Value::Bool(true),
            }
        );
    }

    #[test]
    fn number_to_iter() {
        let value = json!(42);
        let items: Vec<_> = Iter::new(&value).collect();

        assert_eq!(items.len(), 1);
        assert_eq!(
            items[0],
            Element {
                path: String::from(""),
                indices: Vec::new(),
                value: &Value::Number(42.into()),
            }
        );
    }

    #[test]
    fn string_to_iter() {
        let value = json!("Hello there!");
        let items: Vec<_> = Iter::new(&value).collect();

        assert_eq!(items.len(), 1);
        assert_eq!(
            items[0],
            Element {
                path: String::from(""),
                indices: Vec::new(),
                value: &Value::String("Hello there!".into()),
            }
        );
    }

    #[test]
    fn array_to_iter() {
        let value = json!([null, null]);
        let style = StyleBuilder::new().include_array_parents().build();
        let items: Vec<_> = Iter::new(&value).use_style(style).collect();

        assert_eq!(items.len(), 3);
        assert_eq!(
            items[0],
            Element {
                path: String::from(""),
                indices: Vec::new(),
                value: &Value::Array(vec![Value::Null, Value::Null]),
            }
        );
    }

    #[test]
    fn object_to_iter() {
        let value = json!({ "a": true, "b": false });
        let style = StyleBuilder::new().include_object_parents().build();
        let items: Vec<_> = Iter::new(&value).use_style(style).collect();

        assert_eq!(items.len(), 3);
        assert_eq!(
            items[0],
            Element {
                path: String::from(""),
                indices: Vec::new(),
                value: &json!({ "a": true, "b": false }),
            }
        );
    }

    #[test]
    fn can_skip_parents() {
        let value = json!({
            "first": [1, 2, 3],
            "middle": true,
            "last": ["a", "b", "c"],
        });
        let style = StyleBuilder::new()
            .skip_object_parents()
            .skip_array_parents()
            .build();
        let items: Vec<_> = Iter::new(&value).use_style(style).collect();

        assert_eq!(items.len(), 7);
        assert_eq!(
            items[2],
            Element {
                path: String::from("[\"first\"][2]"),
                indices: vec![2],
                value: &Value::Number(3.into()),
            }
        );
        assert_eq!(
            items[5],
            Element {
                path: String::from("[\"last\"][2]"),
                indices: vec![2],
                value: &Value::String("c".into()),
            }
        );
    }

    #[test]
    fn custom_style_on_iter() {
        let value = json!({
            "first": [1, 2, 3],
        });
        let style = StyleBuilder::new()
            .object_key_prefix("!")
            .object_key_suffix("@")
            .show_object_keys_in_path()
            .include_object_parents()
            .array_key_prefix("#")
            .array_key_suffix("$")
            .hide_array_keys_in_path()
            .include_array_parents()
            .build();
        let items: Vec<_> = Iter::new(&value).use_style(style).collect();

        assert_eq!(items.len(), 5);
        assert_eq!(
            items[3],
            Element {
                path: String::from("!first@#$"),
                indices: vec![1],
                value: &Value::Number(2.into()),
            }
        );
    }

    #[test]
    fn complex_format_on_iter() {
        let value = json!({
            "first": [1, 2, 3],
            "middle": true,
            "last": ["a", "b", "c"],
        });
        let style = StyleBuilder::new()
            .include_object_parents()
            .include_array_parents()
            .build();
        let items: Vec<_> = Iter::new(&value).use_style(style).collect();

        assert_eq!(items.len(), 10);
        assert_eq!(
            items[2],
            Element {
                path: String::from("[\"first\"][0]"),
                indices: vec![0],
                value: &Value::Number(1.into()),
            }
        );
        assert_eq!(
            items[5],
            Element {
                path: String::from("[\"last\"]"),
                indices: Vec::new(),
                value: &Value::Array(vec!["a".into(), "b".into(), "c".into()]),
            }
        );
        assert_eq!(
            items[8],
            Element {
                path: String::from("[\"last\"][2]"),
                indices: vec![2],
                value: &Value::String("c".into()),
            }
        );

        // interesting note that "middle" is sorted alphabetically to the last object entry by json!()
        assert_eq!(
            items[9],
            Element {
                path: String::from("[\"middle\"]"),
                indices: Vec::new(),
                value: &Value::Bool(true),
            }
        );
    }

    #[test]
    fn in_a_for_loop() {
        let value = json!({
            "first": [1, 2, 3],
            "middle": true,
            "last": ["a", "b", "c"],
        });

        let mut collection = Vec::new();
        let style = StyleBuilder::new()
            .include_object_parents()
            .include_array_parents()
            .build();
        for item in Iter::new(&value).use_style(style) {
            collection.push(item);
        }

        assert_eq!(collection.len(), 10);
        assert_eq!(
            collection[2],
            Element {
                path: String::from("[\"first\"][0]"),
                indices: vec![0],
                value: &Value::Number(1.into()),
            }
        );
        assert_eq!(
            collection[5],
            Element {
                path: String::from("[\"last\"]"),
                indices: Vec::new(),
                value: &Value::Array(vec!["a".into(), "b".into(), "c".into()]),
            }
        );
        assert_eq!(
            collection[8],
            Element {
                path: String::from("[\"last\"][2]"),
                indices: vec![2],
                value: &Value::String("c".into()),
            }
        );

        // interesting note that "middle" is sorted alphabetically to the last object entry by json!()
        assert_eq!(
            collection[9],
            Element {
                path: String::from("[\"middle\"]"),
                indices: Vec::new(),
                value: &Value::Bool(true),
            }
        );
    }
}