Serialize and deserialize HashMap to JSON in Rust

  • If we have a HashMap we can easily serialize it into a JSON string (which we can save to a file if we want to).
  • And we can deserialize back to HashMap and check that we get back the same data.
[package]
name = "serialize-hashmap"
version = "0.1.0"
edition = "2021"

[dependencies]
serde_json = "1.0.120"

Code

use std::collections::HashMap;

fn main() {
    let mut data_before = HashMap::new();
    data_before.insert(String::from("foo"), 23);
    data_before.insert(String::from("bar"), 42);
    println!("data_before:  {data_before:?}");

    // serialize
    let json_string = serde_json::to_string(&data_before).unwrap();
    println!("serialized:   {json_string}");

    // deserialize
    let data_after: HashMap<String, u32> = serde_json::from_str(&json_string).unwrap();
    println!("deserialized: {data_after:?}");
    assert_eq!(data_before, data_after);

    // doing the same using Turbofish
    let data_turbofish = serde_json::from_str::<HashMap<String, u32>>(&json_string).unwrap();
    println!("turbofish:    {data_turbofish:?}");
    assert_eq!(data_before, data_turbofish);
}

Output

data_before:  {"foo": 23, "bar": 42}
serialized:   {"foo":23,"bar":42}
deserialized: {"foo": 23, "bar": 42}
turbofish:    {"bar": 42, "foo": 23}