Read and deserialize key-value pair JSON into HashMap
-
If we have a JSON file with arbitrary key-value pairs were all the keys are the same type and all the values are the same type then we can read them into a HashMap.
-
In this case all the keys are strings and all the values are integers. (positive integers that can fit in
u16
). -
Centepide has between 15-191 pairs of leggs and the number of pairs is always odd. So there are no Centipedes with 100 leggs.
{
"cat": 4,
"chicken": 2,
"spider": 8,
"ant": 6,
"centipede": 100,
"snake": 0
}
Output
leggs: {"ant": 6, "snake": 0, "centipede": 100, "spider": 8, "cat": 4, "chicken": 2}
turbofish: {"spider": 8, "ant": 6, "centipede": 100, "chicken": 2, "snake": 0, "cat": 4}
Code
use std::collections::HashMap; fn main() { let filename = "data.json"; let content = std::fs::read_to_string(filename).unwrap(); let leggs: HashMap<String, u32> = serde_json::from_str(&content).unwrap(); println!("leggs: {leggs:?}"); // doing the same using Turbofish let turbofish = serde_json::from_str::<HashMap<String, u32>>(&content).unwrap(); println!("turbofish: {turbofish:?}"); assert_eq!(leggs, turbofish); }