Get Json value from plain text without declaring struct first

Suppose I have this .json text:

{
  "name": "John",
  "age": 30,
  "car": false
}

I need to exact the value from "age", without declaring the entire struct first, and use #[derive(Deserialize)]. My struct in text form may be really really long, and I would prefer not to declare the struct with Serde.

Is there any way for me to achieve this?
Thank you.

Yes, see here serde_json::Values (and its associated methods as_[type]).

IMO, that seems like all the more reasons to be more formal about it instead of less.

Why do you want to construct that really really long hashmap where you can ignore all those fields except for the age?

fn extract_age(s: &str) -> serde_json::Result<u32> {
    #[derive(serde::Deserialize)]
    struct Age {
        age: u32,
    }
    let age: Age = serde_json::from_str(s)?;
    Ok(age.age)
}
4 Likes