Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

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"
}

- This example load a file into memory then uses [TODO: Code shorthand span ] . A [TODO: Code shorthand span ] method exists which can read the file without first loading it into memory. I went with [TODO: Code shorthand span ] based off this note from the docs :

"Note that counter to intuition, this function is usually slower than reading a file completely into memory and then applying from _ str or from _ slice on it.

Footnotes And References