home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

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

May 2024
Code
```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
[/Users/alan/.cargo/target/55/19854259915251/_active_nvim_run:23:21] values = JsonConfig {
    alfa: "value from config",
    bravo: "default value for bravo",
}
Code
{
  "alfa": "value from config"
}

An alternate approach that uses a generic JSON structure without validation

═══ § ═══