Rustup - Serde - Read JSON File

08/01/2021, Sun
Categories: #rust

This is an example on using the serde_json library to read JSON data stored in a file. Serde doesn't have a method to directly read from your file directory and get the data from the JSON file, so it will be a two-step process.

Create a new Rust project with

cargo new json-read

Add in the serde_json crate in Cargo.toml:

# ...

[dependencies]
serde_json = "1.0.66"

Then install the dependencies:

cargo build

Create a JSON file that in the root of the project.

[
    {
        "name": "Bob",
        "gender": "male",
        "age": 34
    },
    {
        "name": "Alice",
        "gender": "female",
        "age": 32
    }
]

Read the file with Rust's fs module and then pass in the information to serde to read the JSON.

use std::fs;

fn main() {
    let data = fs::read_to_string("./persons.json")
        .expect("Unable to read file");

    let json: serde_json::Value = serde_json::from_str(&data)
        .expect("JSON does not have correct format.");

    dbg!(json);
}

Execute the program:

cargo r