Skip to content

Instantly share code, notes, and snippets.

@sgherbst
Created April 28, 2021 19:51
Show Gist options
  • Select an option

  • Save sgherbst/32e80e2f60e94db974e13eb30843cf65 to your computer and use it in GitHub Desktop.

Select an option

Save sgherbst/32e80e2f60e94db974e13eb30843cf65 to your computer and use it in GitHub Desktop.
Building a serde_yaml Mapping
// adapted from serde_json example: https://stackoverflow.com/a/39147207
extern crate serde_yaml;
use serde_yaml::{Value, Mapping, Number};
fn main() {
let mut inner_map = Mapping::new();
inner_map.insert(Value::String("x".to_string()), Value::Number(Number::from(10u64)));
inner_map.insert(Value::String("y".to_string()), Value::Number(Number::from(20u64)));
let mut map = Mapping::new();
map.insert(Value::String("key1".to_string()), Value::String("test".to_string()));
map.insert(
Value::String("key2".to_string()),
Value::Sequence(vec![
Value::String("a".to_string()),
Value::String("b".to_string()),
]),
);
map.insert(Value::String("key3".to_string()), Value::Mapping(inner_map));
println!("{}", serde_yaml::to_string(&map).unwrap());
// ---
// key1: test
// key2:
// - a
// - b
// key3:
// x: 10
// y: 20
}
@sgherbst
Copy link
Author

The above code can be directly run in the Rust Playground: https://play.rust-lang.org

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment