- serde_json
- from_str
- Value
Read JSON file
- We would like to read the following simple JSON file:
examples/json/json-read-from-file/data.json
{"x":1,"y":2, "text":"Hello World!"}
- We need serde and serde_json
examples/json/json-read-from-file/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 in two ways.
- Once into a generic serde::Value structure. In this case we need to extract and convert the values.
- Once into a pre-defined struct.
- TODO: show in both cases how to handle cases when a fiedl is missing or the value is incorrect type (eg. we have "x": "qqrq")
- TODO: show in both cases what happens if there are fields in the JSON file that we don't know about in the struct.
- TODO: show lists in the JSON file
- TODO: show deeper structure
examples/json/json-read-from-file/src/main.rs
use std::fs::File; use std::io::Read; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct Point { x: i32, y: i32, text: String, } fn main() { first_read_file(); } fn first_read_file() { let filename = "data.json"; match File::open(filename) { Ok(mut file) => { let mut content = String::new(); file.read_to_string(&mut content).unwrap(); let data: serde_json::Value = serde_json::from_str(&content).expect("JSON parsing error"); dbg!(&data); let text = match data.get("text") { Some(val) => val.as_str().unwrap(), None => panic!("Field text does not exist"), }; println!("{}", text); let x = match data.get("x") { Some(val) => val.as_i64().unwrap(), None => panic!("Field x does not exist"), }; let y = match data.get("y") { Some(val) => val.as_i64().unwrap(), None => panic!("Field y does not exist"), }; println!("{}", x+y); let data: Point = serde_json::from_str(&content).unwrap(); println!("data = {:?}", data); println!("{}", data.x + data.y); println!("{}", data.text); }, Err(error) => { println!("Error opening file {}: {}", filename, error); }, } }
Hello World! 3 data = Point { x: 1, y: 2, text: "Hello World!" } 3 Hello World!