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
//! `flats` is a crate that transforms nested serde `Serialize` types into a one dimensional,
//! flat map of keys and values.
//! Nested structures are represented as map keys that represent structual paths to values
//!
//! ```rust
//! #[macro_use]
//! extern crate serde_json;
//! extern crate flats;
//!
//! use std::collections::BTreeMap;
//! use flats::{flatten_value, Scalar};
//!
//! fn main() {
//!   let flat: BTreeMap<String, Scalar> = flatten_value(
//!     json!({
//!       "name": "John Doe",
//!       "address": {
//!           "city": "nyc"
//!       },
//!       "phones": [
//!         "+44 1234567",
//!         "+44 2345678"
//!       ]
//!     })
//!  );
//!
//!  let mut expected: BTreeMap<String, Scalar> = BTreeMap::new();
//!  expected.insert("name".into(), "John Doe".into());
//!  expected.insert("address.city".into(), "nyc".into());
//!  expected.insert("phones[0]".into(), "+44 1234567".into());
//!  expected.insert("phones[1]".into(), "+44 2345678".into());
//!
//!  assert_eq!(expected, flat);
//! }
//! ```

#![deny(missing_docs)]

extern crate serde;
#[macro_use]
extern crate serde_derive;
#[cfg(test)]
#[macro_use]
extern crate serde_json;
#[cfg(not(test))]
extern crate serde_json;

// Std Lib
use std::collections::BTreeMap;

// Third Party
use serde::Serialize;
use serde_json::Value;

// Ours
mod scalar;
pub use scalar::Scalar;

// re-export exposed type
pub use serde_json::Result;

/// Flattens nested structures into a one dimensional map
///
/// This first serializes the structure to a `serde_json::Value`
/// which may fail, hence the `Result` type.
pub fn flatten<S>(nested: S) -> Result<BTreeMap<String, Scalar>>
where
    S: Serialize,
{
    serde_json::to_value(nested).map(flatten_value)
}

/// Flattens nested `serde_json::Value` instances into a one dimensional map
pub fn flatten_value(value: Value) -> BTreeMap<String, Scalar> {
    fn fold<'a>(
        result: &'a mut BTreeMap<String, Scalar>,
        val: Value,
        path: Option<String>,
    ) -> &'a mut BTreeMap<String, Scalar> {
        match val {
            Value::Object(fields) => {
                for (k, v) in fields.into_iter() {
                    fold(
                        result,
                        v,
                        path.clone()
                            .map(|p| format!("{}.{}", p, k))
                            .or_else(|| Some(k.to_string())),
                    );
                }
            }
            Value::Array(v) => {
                for (idx, elem) in v.into_iter().enumerate().into_iter() {
                    fold(
                        result,
                        elem,
                        path.clone()
                            .map(|p| format!("{}[{}]", p, idx))
                            .or_else(|| Some(format!("[{}]", idx))),
                    );
                }
            }
            Value::Bool(scalar) => {
                result.insert(path.unwrap_or_default(), Scalar::Bool(scalar));
            }
            Value::String(scalar) => {
                result.insert(path.unwrap_or_default(), Scalar::String(scalar));
            }
            Value::Number(scalar) => {
                result.insert(path.unwrap_or_default(), Scalar::Number(scalar));
            }
            Value::Null => {
                result.insert(path.unwrap_or_default(), Scalar::Null);
            }
        };
        result
    }
    fold(&mut BTreeMap::new(), value, None).to_owned()
}

#[cfg(test)]
mod tests {
    use super::{flatten, serde_json, Scalar};
    use std::collections::BTreeMap;

    #[test]
    fn flattens_nested_maps() {
        let result = flatten(json!({
            "foo": {
                "bar": {
                    "baz": 3
                }
            }
        })).unwrap();
        let mut expected: BTreeMap<String, Scalar> = BTreeMap::new();
        expected.insert("foo.bar.baz".into(), 3.into());
        assert_eq!(result, expected)
    }

    #[test]
    fn flattens_to_serializable() {
        let result = flatten(json!({
            "foo": {
                "bar": {
                    "baz": 3
                }
            }
        })).unwrap();
        assert_eq!(
            serde_json::to_string(&result).unwrap(),
            r#"{"foo.bar.baz":3}"#
        )
    }
}