- from_reader
Read JSON file using from_reader manually
cargo run ../person.json
examples/json/person.json
{ "fname": "Foo", "lname": "Bar", "year": 1992, "height": 178.2, "married": true, "numbers": [23, 19, 42], "children": [ { "name": "Alpha", "birthdate": 2020 }, { "name": "Beta", "birthdate": 2022 } ] }
examples/json/person-future.json
{ "fname": "Foo", "lname": "Bar", "year": 1992, "height": 178.2, "married": true, "numbers": [23, 19, 42], "children": [ { "name": "Alpha", "birthdate": 2020 }, { "name": "Beta", "birthdate": 2022 }, { "name": "Future" } ] }
examples/json/read-json-from-reader-manually/Cargo.toml
[package] name = "json-read-from-reader" 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"
examples/json/read-json-from-reader-manually/src/main.rs
use std::fs::File; fn main() { let filename = get_filename(); let data = match File::open(&filename) { Ok(file) => { let data: serde_json::Value = serde_json::from_reader(&file).expect("JSON parsing error"); data } Err(error) => { eprintln!("Error opening file {}: {}", filename, error); std::process::exit(1); } }; println!("{:#?}", &data); assert_eq!(data.get("fname").unwrap().as_str().unwrap(), "Foo"); assert_eq!(data["lname"].as_str().unwrap(), "Bar"); assert_eq!(data["height"].as_f64().unwrap(), 178.2); assert_eq!(data["year"].as_u64().unwrap(), 1992); assert_eq!(data["numbers"].as_array().unwrap().len(), 3); assert_eq!(data["numbers"][0].as_u64().unwrap(), 23); assert!(data["married"].as_bool().unwrap()); assert_eq!(data["children"].as_array().unwrap().len(), 2); assert_eq!(data["children"][0]["name"].as_str().unwrap(), "Alpha"); } fn get_filename() -> String { let args: Vec<String> = std::env::args().collect(); if args.len() != 2 { eprintln!("Usage: {} FILENAME", args[0]); std::process::exit(1); } args[1].to_owned() }
Object { "children": Array [ Object { "birthdate": Number(2020), "name": String("Alpha"), }, Object { "birthdate": Number(2022), "name": String("Beta"), }, ], "fname": String("Foo"), "height": Number(178.2), "lname": String("Bar"), "married": Bool(true), "numbers": Array [ Number(23), Number(19), Number(42), ], "year": Number(1992), }