How to Deserialize Nested JSON in Rust

Deserialize nested JSON in Rust by defining structs with the serde derive macro and parsing the string with serde_json::from_str.

Use the serde crate to derive Deserialize on structs that mirror your JSON hierarchy, then call serde_json::from_str to parse the string into the root type.

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Config {
    output_mode: Mode,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
enum Mode {
    Default,
    Simple,
}

fn main() {
    let json = r#"{"output_mode": "simple"}"#;
    let config: Config = serde_json::from_str(json).unwrap();
    println!("{:?}", config.output_mode);
}