How to Deserialize into a HashMap with Serde

Define a struct with a `HashMap` field and derive `Deserialize` to parse JSON into it. Serde automatically handles the key-value pairs when the JSON structure matches your struct definition.

How to Deserialize into a HashMap with Serde

Define a struct with a HashMap field and derive Deserialize to parse JSON into it. Serde automatically handles the key-value pairs when the JSON structure matches your struct definition.

use serde::Deserialize;
use std::collections::HashMap;

#[derive(Deserialize)]
struct Config {
    scores: HashMap<String, i32>,
}

fn main() {
    let json = r#"{"scores": {"Blue": 10, "Yellow": 50}}"#;
    let config: Config = serde_json::from_str(json).unwrap();
}