Rust

Untyped JSON with serde_json::Value

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
When you don't know the JSON shape up-front, parse into `serde_json::Value` and navigate via index / get(). Type-safe pattern matching converts back to Rust types.
Rust
Raw
use serde_json::{json, Value};

fn main() {
    // Build untyped JSON inline with the json! macro
    let data = json!({
        "name": "Alice",
        "age": 30,
        "roles": ["admin", "editor"],
        "address": { "city": "Austin" }
    });

    // Read fields by key / index
    println!("{}", data["name"]);                       // "Alice"
    println!("{}", data["roles"][0]);                   // "admin"
    println!("{}", data["address"]["city"]);            // "Austin"
    println!("{:?}", data.get("missing"));              // None

    // Convert with as_*
    if let Some(age) = data["age"].as_u64() {
        println!("age = {age}");
    }

    // Parse text into Value, then navigate
    let raw = r#"{"a": {"b": [1, 2, 3]}}"#;
    let v: Value = serde_json::from_str(raw).unwrap();
    if let Some(arr) = v["a"]["b"].as_array() {
        let sum: u64 = arr.iter().filter_map(|x| x.as_u64()).sum();
        println!("sum = {sum}");                        // 6
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.