home ~ projects ~ socials

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

Notes

  • This example load a file into memory then uses .from_str(). A .from_reader() method exists which can read the file without first loading it into memory. I went with .from_str() 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.

-- end of line --

References