Read JSON to Vector

  • Sometimes the root of the JSON struct is a list that contains structures of key-value pairs. We can read that into a vector of structs.
  • We already saw this, but then the values were plain strings. Now they are parsed into a struct.
[
    {
        "name": "Foo",
        "number": 10
    },
    {
        "name": "Bar",
        "number": 20
    }
]

Code

use serde::Deserialize;

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct Person {
    name: String,
    number: u32,
}

fn main() {
    let filename = "data.json";
    let content = std::fs::read_to_string(filename).unwrap();
    let data = serde_json::from_str::<Vec<Person>>(&content).expect("JSON parsing error");
    println!("{:#?}", data);
}

Output

[
    Person {
        name: "Foo",
        number: 10,
    },
    Person {
        name: "Bar",
        number: 20,
    },
]