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
An alternate approach that uses a generic JSON structure
without validation