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();
}
Deserializing into a HashMap with Serde converts a JSON object directly into a Rust HashMap. It matters because it lets you read configuration files or API responses without manually parsing every single key. Think of it like pouring a bag of mixed Lego bricks directly into a sorted bin where the color of the brick determines which slot it falls into.