- serde_json
- from_str
- Value
- as_object
- as_str
- as_i64
Read Simple JSON file manually
- We would like to read the following simple JSON file:
examples/json/read-simple-json-manually/data.json
{ "x":1, "y":2, "text":"Hello World!" }
- We need serde and serde_json
cargo add serde_json cargo add serde -F derive
examples/json/read-simple-json-manually/Cargo.toml
[package] name = "json-read-from-file" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0.97"
- We first open the file and read the content of the file.
- Then we parse the string as some generic JSON data into a generic serde::Value structure. serde::Value is an enum that can hold any value.
- In this case we need to extract and convert the values.
examples/json/read-simple-json-manually/src/main.rs
fn main() { let filename = "data.json"; let content = std::fs::read_to_string(filename).unwrap(); let data: serde_json::Value = serde_json::from_str(&content).expect("JSON parsing error"); println!("data: {}", data); println!(); if data.is_object() { for key in data.as_object().unwrap().keys() { println!("{:#?}", key); } } println!(); match data.get("text") { None => (), Some(text) => { println!("this is text: {}", text.is_string()); println!("this is text: {}", text.is_u64()); } } println!(); let text = match data.get("text") { Some(val) => val.as_str().unwrap(), None => panic!("Field text does not exist"), }; println!("text: {text}"); let x = match data.get("x") { Some(val) => val.as_i64().unwrap(), None => panic!("Field x does not exist"), }; println!("x: {x}"); let y = match data.get("y") { Some(val) => val.as_i64().unwrap(), None => panic!("Field y does not exist"), }; println!("y: {y}"); println!("x+y = {}", x + y); }
data: {"text":"Hello World!","x":1,"y":2} "text" "x" "y" this is text: true this is text: false text: Hello World! x: 1 y: 2 x+y = 3