Read Simple JSON file manually



examples/json/read-simple-json-manually/data.json
{
    "x":1,
    "y":2,
    "text":"Hello World!"
}

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"

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