Untyped JSON with Value in Rust
When the shape is unknown, Value and the json! macro handle it dynamically.
use serde_json::{json, Value};
fn main() -> Result<(), serde_json::Error> {
let payload = json!({
"lang": "sql",
"tours": ["basics", "joins"],
"steps": 45
});
println!("{}", payload["lang"].as_str().unwrap_or("?"));
println!("{:?}", payload["steps"].as_u64());
println!("{}", payload["missing"].is_null());
let parsed: Value = serde_json::from_str(r#"{"ok":true}"#)?;
println!("{:?}", parsed["ok"].as_bool());
Ok(())
}
How it works
json!builds aValuewith JSON-ish syntax.- Indexing returns
Value::Nullrather than panicking. as_strandas_u64attempt a typed read.
Keywords and builtins used here
OkResultValuefnletmainuse
The run, in numbers
- Lines
- 17
- Characters to type
- 421
- Tokens
- 160
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 96 seconds.
Step 2 of 3 in Deriving, step 2 of 11 in Serde & JSON.