[][src]Function serde_value_flatten::to_flatten_maptree

pub fn to_flatten_maptree<T: ?Sized>(
    key_separator: &str,
    prefix: Option<&str>,
    src: &T
) -> Result<BTreeMap<Value, Value>, SerializerError> where
    T: Serialize

Function to flatten any structure which implement the serde::Serialize.

Keys or attributes names will be will concatenated as path (e.g: { a: {b: 5}} -> { a_b: 5 }).

Configuration

  • key_separator: Separator to use at each level change.
  • prefix: Prefix to use on the first level before the attribute / key / index name

Example

#[derive(Serialize, Clone, Debug)]
struct SubFoo {
    a: String,
    b: u64,
}
 
#[derive(Serialize, Clone, Debug)]
struct Foo {
    a: String,
    b: f64,
    c: Vec<i8>,
    d: SubFoo,
}
 
fn main() {
    let foo = Foo { a: "test".into(), b: 0.5, c: vec![5, 9], d: SubFoo { a: "subtest".into(), b: 695217 } };
    let ser = serde_value_flatten::to_flatten_maptree("|", None, &foo).unwrap();
 
    println!("{}", serde_json::to_string_pretty(&ser).unwrap());
}

Output:

{
  "a": "test",
  "b": 0.5,
  "c|0": 5,
  "c|1": 9,
  "d|a": "subtest",
  "d|b": 695217
}