Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Load And Validate A JSON Config File With A Specific Format In Rust

rust
```cargo
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
```

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

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct JsonConfig{
    alfa: String,
    #[serde(default = "default_bravo")]
    bravo: String
}

fn main() {
  let config_path = PathBuf::from("config-sample.json");
  let config = load_config_file(&config_path);
  match config {
    Ok(values) => { dbg!(values); () }
    Err(e) => println!("{}", e)
  }
}

fn default_bravo() -> String {
  "default value for bravo".to_string()
}

fn load_config_file(path: &PathBuf) -> Result<JsonConfig, String> {
    match path.try_exists() {
        Ok(exists) => {
            if exists == true {
              match fs::read_to_string(&path) {
                Ok(text) => {
                  match serde_json::from_str::<JsonConfig>(text.as_str()) {
                    Ok(data) => { Ok(data) },
                    Err(e) => {
                      Err(format!("Could not parse JSON file: {}\n{}", &path.display(), e)) 
                    }
                  }
                }, 
                Err(e) => {
                  Err(format!("Could not read JSON file: {}\n{}", &path.display(), e)) 
                }
              }
            } else {
                Err(format!("Could not read JSON file: {}", &path.display())) 
            }
        }
        Err(e) => {
          Err(format!("{}", e)) 
        }
    }
}
results start
json
{
  "alfa": "value from config"
}

An alternate approach that uses a generic JSON structure without validation