I am attempting to turn a flat structure like the following:
let flat = vec![
Foo {
a: "abc1".to_owned(),
b: "efg1".to_owned(),
c: "yyyy".to_owned(),
d: "aaaa".to_owned(),
},
Foo {
a: "abc1".to_owned(),
b: "efg2".to_owned(),
c: "zzzz".to_owned(),
d: "bbbb".to_owned(),
}];
into a nested JSON object through serde_json that looks something like:
{
"abc1": {
"efg1": {
"c": "hij1",
"d": "aaaa",
},
"efg2": {
"c": "zzzz",
"d": "bbbb",
},
}
}
(The values b are guaranteed to be unique within the array)
If I had needed only one layer, I would do something like this:
let map = flat.into_iter().map(|input| (input.a, NewType {
b: input.b,
c: input.c,
d: input.d,
})).collect::<Hashmap<String, NewType>>();
let out = serde_json::to_string(map).unwrap();
However, this doesn't seem to scale to multiple layers (i.e. (String, (String, NewType)) can't collect into Hashmap<String, Hashmap<String, NewType>>)
Is there a better way than manually looping and inserting entries into the hashmaps, before turning them into json?
structfor this with a fixed number of fields. If you want more, you're going to have to make different variants; this is a wasted opportunity and would've been a perfect use case for aVeccontaining the branch pathbis unique, not aVecwith branch paths? I specifically put in serde_json as context as I'm not sure what the best way to accomplish this is, thanks.Foo {...}), you had a vector indicating the path to go (i.e.vec!['abc1', 'efg1', ...]) you would then be able to iteratively walk this path and generate your structure. As it is, sadly, short of implementing something likeInto<Vec<String>>to be able to recurse, you're going to be stuck with procedurally walking down the tree for each element, I think