Match Walks Recursive JSON Value Trees

match destructures a recursive Value enum, printing arrays and nested objects with growing indentation until every leaf has been visited.

RustData Integrity

Code

rustsnippet
43 lines
#[derive(Debug)]
enum Value {
    Null,
    Bool(bool),
    Number(f64),
    Text(String),
    Array(Vec<Value>),
    Object(Vec<(String, Value)>),
}

// match walks the JSON-like tree recursively, one arm per shape
fn summarize(value: &Value, depth: usize) {
    match value {
        Value::Null => println!("{:indent$}null", "", indent = depth * 2),
        Value::Bool(flag) => println!("{:indent$}bool {flag}", "", indent = depth * 2),
        Value::Number(n) => println!("{:indent$}number {n}", "", indent = depth * 2),
        Value::Text(s) => println!("{:indent$}text {s:?} ({})", "", s.len(), indent = depth * 2),
        Value::Array(items) => {
            println!("{:indent$}array len {}", "", items.len(), indent = depth * 2);
            for item in items {
                summarize(item, depth + 1);
            }
        }
        Value::Object(pairs) => {
            println!("{:indent$}object len {}", "", pairs.len(), indent = depth * 2);
            for (key, nested) in pairs {
                println!("{:indent$}key {key}:", "", indent = (depth + 1) * 2);
                summarize(nested, depth + 2);
            }
        }
    }
}

fn main() {
    let config = Value::Object(vec![
        ("retries".into(), Value::Number(3.0)),
        ("verbose".into(), Value::Bool(true)),
        ("tags".into(), Value::Array(vec![Value::Text("eu".into()), Value::Text("prod".into())])),
        ("cache".into(), Value::Object(vec![("ttl".into(), Value::Number(30.0))])),
        ("marker".into(), Value::Null),
    ]);
    summarize(&config, 0);
}

What to notice first — Match Walks Recursive JSON Value Trees

Match Walks Recursive JSON Value Trees is built around the functions summarize and main.

The file repeats itself only inside for item in items. A match spells out every case; omit one and the code does not compile.

Caveats

  • Runs on the bundled standard library alone; there is no extra setup step at all.

Putting it to use

The entry-point signature is fn summarize(value: &Value, depth: usize)

Running the file executes main, which drives summarize in order.

Core lines

Value::Object(pairs) => {
    println!("{:indent$}object len {}", "", pairs.len(), indent = depth * 2);
    for (key, nested) in pairs {
        println!("{:indent$}key {key}:", "", indent = (depth + 1) * 2);
        summarize(nested, depth + 2);
    }
}
Value::Array(items) => {
    println!("{:indent$}array len {}", "", items.len(), indent = depth * 2);
    for item in items {
        summarize(item, depth + 1);
    }
}

Interactive Tools for This Topic

FAQ

How do you run Match Walks Recursive JSON Value Trees?
Direct execution is enough; the script has no external requirements.