How to parse yaml file with rust
to parse a YAML file with Rust, you can use the serde_yaml
crate.
Here's an example of how to parse a YAML file in Rust using serde_yaml
parse yaml file with rust
use serde::Deserialize; use serde_yaml::{from_reader, Value}; use std::fs::File; #[derive(Deserialize)] struct Config { name: String, age: u8, hobbies: Vec<String>, } fn main() -> Result<(), Box<dyn std::error::Error>> { let file = File::open("config.yaml")?; let config: Config = from_reader(file)?; println!("Name: {}", config.name); println!("Age: {}", config.age); println!("Hobbies: {:?}", config.hobbies); Ok(()) }
This example defines a struct called Config
that represents the structure of the YAML file.The Config
struct is annotated with #[derive(Deserialize)]
, which tells the serde
crate to generate a function that can deserialize a Config
from a YAML file.
The example then opens the config.yaml
file and uses the from_reader
function to deserialize the file into a Config
struct.
Finally, the example prints the fields of the Config
struct to the console.
You can also use the serde_yaml
crate to parse a YAML string in memory, rather than reading from a file. To do this, you can use the from_str
function instead of the from_reader
function.