August 2023
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 Deserialize;
use fs;
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