Load A JSON Config File In Rust With serde

This is how I'm loading config options in from a JSON file in Rust:

Code
use serde::Deserialize;
use std::fs;
use std::path::PathBuf;

#[derive(Deserialize, Debug)]
pub struct Config {
    alfa: String,
    bravo: String,
}

fn main() {
    if let Some(config) = load_config(PathBuf::from("config.json")) {
        dbg!(config);
    } else {
        println!("Could not load config");
    }
}

pub fn load_config(path: PathBuf) -> Option<Config> {
    if let Ok(data) = fs::read_to_string(path) {
        if let Ok(config) = serde_json::from_str::<Config>(data.as_str()) {
            Some(config)
        } else {
            None
        }
    } else {
        None
    }
}
Notes
  • This requires the crates:

    cargo add serde --features "derive"

    cargo add serde_json

  • This approach requires defining the strut the JSON gets loaded into in advance. I think there are ways to do it without that. I prefer making the structure explicit.

  • The value that comes back from `load_config()`` is an option. The code in `main()`` checks to see if it loaded and works from there.