Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Read/Load A JSON File In Rust

Cargo.toml dependencies

[dependencies]
serde = { version = "1.0.105", features = ["derive"] }
serde_json = { version = "1.0.105" }

File: src/main.rs

use serde::Deserialize;
use std::fs;

#[derive(Deserialize, Debug)]
struct Widget {
    key: String,
}

fn main() {
    let data = fs::read_to_string("example.json").unwrap();
    let w: Widget = serde_json::from_str(data.as_str()).unwrap();
    dbg!(w);
}

File: example.json

{
  "key": "alfa"
}

References