# JSON (`serde/json`)

JSON exposes comptime-specialized struct codecs and the owning `JsonValue`
dynamic tree. The first two snippets are integration fragments; the complete
configuration program and its tests follow under “Validate a configuration”.

## Structured values from trusted input

```vex
import { jsonMarshal, jsonUnmarshal } from "serde/json";

struct User {
    public:
    id: i64,
    name: string,
}

let source = User { id: 7, name: "Ada" };
let encoded = jsonMarshal(&source);
let! decoded = User { id: 0, name: "" };
jsonUnmarshal(encoded.raw_ptr() as Ptr<u8>, encoded.len() as u64, &decoded!);
```

`jsonMarshal<T>` and `jsonUnmarshal<T>` specialize field traversal from comptime
type information. They do not require derive macros or runtime field maps.
This example decodes bytes just produced by the serializer. `jsonUnmarshal`
is a trusted-data path; it is not a substitute for checked parsing of an
external request or file.

## Dynamic values and safe parsing

```vex
import {
    jsonParseDynamicSafe,
    jsonStringifyDynamic,
    jsonStringifyDynamicPretty,
} from "serde/json";

match jsonParseDynamicSafe("{\"items\":[1,true,null]}") {
    Ok(value) => {
        $println(jsonStringifyDynamic(&value));
        $println(jsonStringifyDynamicPretty(&value));
    }
    Err(failure) => { $println(failure.message()); }
}
```

`JsonValue` provides `is*` predicates, scalar accessors, object `get`, array
`at` and `len`. The safe path returns `Result<JsonValue, DecodeError>` and rejects trailing tokens, malformed numbers,
invalid escapes, unpaired Unicode surrogates and malformed arrays/objects.

Finite f64 values use the canonical shortest-roundtrip `strconv` formatter,
so serialization preserves every representable value without fixed trailing
zeros or a temporary string. Because RFC 8259 has no NaN or infinity number,
the current infallible serializer emits `null` for non-finite IEEE values.

The 2026-08-21 M2 Max O3 observable `BenchCtx.iter` baseline measured a small
coordinate struct at about 14.59 ns to encode and 27.72 ns to decode; dynamic
parse measured about 453 ns.
These are local benchmark samples, not portable guarantees.

## Look up and validate fields

These methods borrow the dynamic tree through `self: &JsonValue`:

| Method | Return type | Contract |
| --- | --- | --- |
| `isNull()`, `isBool()`, `isNum()`, `isStr()`, `isArray()`, `isObject()` | `bool` | Check the exact variant before reading its value |
| `get(key: string)` | `Option<&JsonValue>` | Borrow an object member; `None` for a missing key or a non-object |
| `at(index: usize)` | `Option<&JsonValue>` | Borrow an array element; `None` for an invalid index or a non-array |
| `asBool()` | `bool` | Return the boolean; other variants return `false` |
| `asNum()` | `f64` | Return the number; other variants return `0.0` |
| `asString()` | `string` | Return an owning string clone; other variants return an empty string |
| `len()` | `usize` | Return array length or object member count; other variants return zero |

`get` and `at` return borrowed references, not cloned subtrees. Keep the parsed
root alive while using them. A scalar accessor's default does not establish
that a field had the requested type: use `isBool()` before `asBool()`, for
example. Checking only the resulting boolean would conflate an invalid field
with a valid `false` configuration.

## Validate a configuration and test it

This complete example requires an `enabled` boolean, preserves parse errors,
and applies a small resource budget. A valid `false` is accepted; a missing
field or a string is rejected. Keep these three files in the same directory.

```vex [config.vx]
import { DecodeError, DecodeLimits, jsonParseDynamicWithLimits } from "serde/json";

export enum ConfigError {
    InvalidJson(DecodeError),
    ExpectedObject,
    MissingEnabled,
    EnabledNotBool,
}

// Accept a JSON object only when its required enabled member is a boolean.
export fn parseEnabled(input: string): Result<bool, ConfigError> {
    let! limits = DecodeLimits.standard();
    limits.maxTotalBytes = 1024 as usize;
    limits.maxDepth = 8 as usize;
    limits.maxNodes = 64 as usize;
    let document = match jsonParseDynamicWithLimits(input, limits) {
        Ok(value) => value,
        Err(failure) => return Err(ConfigError.InvalidJson(failure)),
    };
    if !document.isObject() { return Err(ConfigError.ExpectedObject); }
    let enabled = match document.get("enabled") {
        Some(value) => value,
        None => return Err(ConfigError.MissingEnabled),
    };
    // asBool() defaults non-booleans to false, so check the exact type first.
    if !enabled.isBool() { return Err(ConfigError.EnabledNotBool); }
    return Ok(enabled.asBool());
}
```

```vex [config-demo.vx]
import { ConfigError, parseEnabled } from "./config.vx";

fn show(input: string) {
    match parseEnabled(input) {
        Ok(enabled) => { $println(f"accepted: enabled={enabled}"); },
        Err(ConfigError.InvalidJson(failure)) => {
            $println(f"rejected: {failure.message()}");
        },
        Err(ConfigError.ExpectedObject) => { $println("rejected: expected an object"); },
        Err(ConfigError.MissingEnabled) => { $println("rejected: missing enabled"); },
        Err(ConfigError.EnabledNotBool) => { $println("rejected: enabled must be boolean"); },
    };
}

fn main(): i32 {
    show("{\"enabled\":true}");
    show("{}");
    show("{\"enabled\":\"true\"}");
    show("{\"enabled\":");
    return 0;
}
```

Run `vex run config-demo.vx`. It prints an accepted `enabled=true` result,
followed by rejections for a missing field, a string field and truncated JSON.
The parsed tree owns its fields until `parseEnabled` returns; the returned
boolean is independent of that tree.

```vex [config.test.vx]
import { ConfigError, parseEnabled } from "./config.vx";

fn test_enabled_true(): bool {
    return match parseEnabled("{\"enabled\":true}") {
        Ok(value) => value,
        Err(_) => false,
    };
}

fn test_enabled_false(): bool {
    return match parseEnabled("{\"enabled\":false}") {
        Ok(value) => !value,
        Err(_) => false,
    };
}

fn test_enabled_missing(): bool {
    return match parseEnabled("{}") {
        Err(ConfigError.MissingEnabled) => true,
        _ => false,
    };
}

fn test_enabled_string(): bool {
    return match parseEnabled("{\"enabled\":\"true\"}") {
        Err(ConfigError.EnabledNotBool) => true,
        _ => false,
    };
}

fn test_enabled_malformed(): bool {
    return match parseEnabled("{\"enabled\":") {
        Err(ConfigError.InvalidJson(_)) => true,
        _ => false,
    };
}

fn test_enabled_nonobject(): bool {
    return match parseEnabled("true") {
        Err(ConfigError.ExpectedObject) => true,
        _ => false,
    };
}
```

Run `vex test --run test_enabled config.test.vx`. All six cases should pass,
including a valid `false`, malformed JSON and a non-object root. Extra object
members are ignored by this schema; define a stricter policy if your protocol
requires one.

## Application-specific resource limits

`jsonParseDynamicSafe` uses `DecodeLimits.standard()`. Choose tighter limits
for a small configuration or request body with `jsonParseDynamicWithLimits`:

```vex
import { DecodeLimits, jsonParseDynamicWithLimits } from "serde/json";

let! limits = DecodeLimits.standard();
limits.maxTotalBytes = 64 * 1024 as usize;
limits.maxDepth = 16 as usize;
limits.maxNodes = 4096 as usize;
match jsonParseDynamicWithLimits("{\"ready\":true}", limits) {
    Ok(value) => { $println(value.len()); },
    Err(failure) => {
        $println(failure.message());
        $println(failure.offset);
    },
};
```

Validation completes before the owning dynamic tree is allocated. The input
`string` has already been materialized before the call; bound the network/file
read as well if the transport must not allocate a large input. These limits
control bytes, nesting and nodes, not the application schema. Check required
keys, value types and ranges after parsing.

Streaming APIs and complete official corpus qualification remain separate
work from the implemented bounded parse surface.
