typestar

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

  1. json! builds a Value with JSON-ish syntax.
  2. Indexing returns Value::Null rather than panicking.
  3. as_str and as_u64 attempt a typed read.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Deriving, step 2 of 11 in Serde & JSON.

← Previous Next →