Search code examples
rustyamlrust-crates

How do you read a YAML file in Rust?


I've poked the serde-yaml and yaml-rust crates a bit, but I haven't seen any examples.


Solution

  • serde-yaml's documentation has the following 4 functions:

    • from_reader — Deserialize an instance of type T from an IO stream of YAML.
    • from_slice — Deserialize an instance of type T from bytes of YAML text.
    • from_str — Deserialize an instance of type T from a string of YAML text.
    • from_value — Interpret a serde_yaml::Value as an instance of type T.

    Using from_reader as an example:

    use serde_yaml; // 0.8.7
    
    fn main() -> Result<(), Box<dyn std::error::Error>> {
        let f = std::fs::File::open("something.yaml")?;
        let d: String = serde_yaml::from_reader(f)?;
        println!("Read YAML string: {}", d);
        Ok(())
    }
    

    something.yaml:

    "I am YAML"
    

    You can deserialize into the looser-typed Value if you don't know your format (String in this example), but be sure to read the Serde guide for full details of how to do type-directed serialization and deserialization instead.

    See also:

    In general, using any Serde format is pretty much the same as all the rest.