This library is in flux. APIs may change without notice. Generated from source with koruc 0.1.7 on 11/17/2026.

JSON

import std/json

std/json - JSON encoding and decoding

json.kz · 22 tors

std/json - JSON encoding and decoding - `~part parse`/`~part emit`: schema-directed compile-time transforms. - `~part dom` (json.dom.kz): runtime document model — parse to a traversable tree, key iteration, typed descent, serializer.

Phantom lifecycles

Derived from the phantom labels in the declarations below — state! issues an obligation the compiler will chase, !state discharges it, a bare state holds it without moving it. Nothing here is hand-drawn.

JsonObject 1 state building!
string 3 states emitted!
Document 1 state open!

JsonNode carries the label <*> with no obligation attached — a dimension, not a lifecycle.

object.new

<building!> koru_std/json.kz:40

object.set

<building> koru_std/json.kz:58

object.finish

<!building> koru_std/json.kz:101

array.new

<building!> koru_std/json.kz:114

array.push

<building> koru_std/json.kz:132

array.finish

<!building> koru_std/json.kz:168

~part parse koru_std/json.parse.kz

Koru Standard Library: the `parse` part of json.kz — schema-directed compile-time JSON parsing as control flow. Joined via `~part parse` in json.kz; merged into the json module at load. The `ok` branch's destructure IS the schema — the same license std/regex:match takes with named groups (the destructure names the payload; a type on a field is a conversion at the splice, and `sub` — meaningless for a text span — is a nested object here): std/json:parse(input: body) | ok { name: string, age: i64, addr: { city: string } } |> greet(name) | malformed { message, offset } |> report(message, offset) Field grammar: a bare leaf (`name`) delivers the value's raw JSON span; `string` delivers the decoded inner text (escapes resolved); `bool`, the int types, and the float types convert at the splice; `?T` admits a missing key or a literal null; `[]T` is an array of T (T may itself be `?`/`[]`/`{...}` — `{...}` inside type_text is a nested object shape); `name: { ... }` is a nested object. Undeclared keys are skipped (JSON convention — strict both-ways is a pinned follow-up); duplicate keys take the last; every declared required key must appear or the parse fails. Ownership is SCOPED: allocations (decoded strings, arrays) land on a per-site arena that is deinit'd when the branch's chain exits — field values are valid inside the branch and die with it (the same contract yyjson's `close` draws, enforced by scope instead of a phantom). A produced value that retains a field slice is dangling — hand long-lived data an owned copy before it leaves the branch. The transform compiles that schema into a bespoke recursive-descent parser: one generated fn per object shape, typed readers per field, a generic value-skipper for undeclared keys, and a dispatch that hands the assembled payload struct to the `ok` body or routes failure to `malformed`. No DOM is materialized — fields land as typed values in the branch. This is the direct competitor of a navigation API (yyjson's parse→root→get→as.* chain): schema known at compile time means the tree is never built. Keys are compared raw — an escape inside a JSON key does not match its identifier yet (cut 2). A destructure-less `| ok v` is recognizer mode: the input must be exactly one JSON value, and the binding carries the consumed span.

parse

comptimetransform <*> koru_std/json.parse.kz:42

~part emit koru_std/json.emit.kz

Koru Standard Library: the `emit` part of json.kz — schema-directed compile-time JSON emission as control flow. Joined via `~part emit` in json.kz; merged into the json module at load. `std/json:emit` is the write-side twin of `std/json:parse`: the record literal at the `value:` position IS the output schema — keys are the JSON key names, and each value expression's type is resolved at compile time from the bindings in scope at the site: std/json:emit(value: { service: service, port: port, tls: tls }) | ok body |> send(body) |> std/json:emit.free(text: body) A bare identifier `emit(value: cfg)` emits every field of a branch-payload record bound upstream (`| ok cfg` on a tor whose payload declares named fields). Value grammar: a binding name resolved through scopeAtSite (destructure fields, `| branch name` payload binds, `: name` return binds, impl input fields), a `binding.field` path into a record payload, a nested `{...}` record literal, or a string/number/bool/null literal. Supported field types: `string` (escaped at the splice), `bool`, the int types, the float types (non-finite emits `null` — JSON cannot spell inf/nan), `?T` (null or inner), `[]T`. A bare destructure leaf has no type — it cannot be resolved and is refused with a teaching error. Ownership: `ok` mints `string<emitted!>`, discharged ONLY by `std/json:emit.free` — the same contract as yyjson's `render`/`render.free`, one allocation, koru_allocator-owned, no arena. The output is independent of every input binding's lifetime. The transform emits no DOM and no builder tree: a per-site escaping writer, a number writer, and an inline byte-append sequence specialized to the resolved schema. The tor decl declares the USER surface: `emit(...): body` binds a string carrying <emitted!>, discharged by `emit.free`. The transform proc returns SiteResult internally — the decl's return is what the call site produces.

emit

comptimetransform <emitted!> koru_std/json.emit.kz:38

emit.free

<!emitted> koru_std/json.emit.kz:43

~part emithelpers koru_std/json.emithelpers.kz

Koru Standard Library: JSON — emit helpers. Joined via `~part emithelpers` in json.kz; merged into the json module at load. Holds the emit transform's helper container so the driver stays under the line wall — same split as json.parsehelpers.kz.

~part emitcap koru_std/json.emitcap.kz

Koru Standard Library: JSON — emit capacity estimates. Joined via `~part emitcap` in json.kz; merged into the json module at load. EmitCap walks the same resolved schema EmitH walks and produces a usize-typed Zig expression bounding the site's output bytes, so the emitted writer can ensureTotalCapacity once instead of growing by doubling. Static framing (keys, quotes, braces, commas, literal bytes) folds to comptime literals; string exprs contribute .len; numbers take the spec bounds (20 int / 32 float / 5 bool / 4 null); arrays pre-pass their elements in a labeled block. Escapes can still outgrow the estimate — it is a reservation hint, not a contract.

~part emitdrive koru_std/json.emitdrive.kz

Koru Standard Library: JSON — EmitDrive, the site driver shared by `emit`, `emit.ln`, and `emit.into`. Joined via `~part emitdrive` in json.kz; merged into the json module at load. Schema resolution stays in EmitH, capacity hints in EmitCap; `mode` is a comptime selector that swaps the writer prelude (heap ArrayList / per-callsite threadlocal scratch / caller-provided slice) and the epilogue break value. emit.into is the zero-copy arm: the caller hands a writable slice (the connection's send region) and gets back `usize` — bytes written, snprintf contract. The phantom system cannot honestly express "borrows caller's buf", so no slice return and no obligation to discharge.

~part emitjs koru_std/json.emitjs.kz

Koru Standard Library: JSON — emit JS-backend twin. Joined via `~part emitjs` in json.kz; merged into the json module at load. Split out of json.emit.kz to keep the driver under its line pin. JS twin: not yet implemented — refuse loudly rather than emit Zig text into a JS output (where it would surface as a syntax error).

~part emitln koru_std/json.emitln.kz

Koru Standard Library: JSON — the scratch-buffer emit arms' decls. Joined via `~part emitln` in json.kz; merged into the json module at load. EmitDrive (the shared site driver, all three writer modes) lives in json.emitdrive.kz — this file pins only the two non-allocating call surfaces. emit.ln is the write-side twin of fmt:ln's discipline: the site emits into a per-callsite threadlocal scratch (default 4096 bytes, `[size(Nk)]` / `[size(Nm)]` on the call resizes THIS site) and binds `string<scratch@scoped>` — the borrow dies with the frame, so it can feed a synchronous sink (a send buffer, a file write) but can never be stored or returned. No heap allocation, no emit.free — scratch needs no discharge. Overflow panics naming the site's size, same as fmt:ln. CAVEAT (shared with fmt:ln): scratch@scoped promises frame-safety but same-callsite REENTRANCY (recursion, a callback between emit and consume) overwrites the buffer while the outer value is still alive — silent corruption the phantom cannot see. Intended use only: emit → consume with nothing reentrant between. emit.into is the zero-copy arm: `buf:` names a writable []u8 slice (spliced verbatim into the generated writer — a connection's send region, a stack array) and the site returns `usize`, bytes written. snprintf contract: no slice return, because the phantom system cannot honestly express "borrows caller's buf". Args resolve BY NAME, so `value:` and `buf:` may arrive in either order. Overflow panics naming emit.into; the buffer length is runtime, so the message says "exceeds the provided buffer". No reserve pass — same as emit.ln. std/json:emit.ln [size(8k)] (value: { posts: ps }): out |> orisha:respond(req, status: 200, body: out, ...): r std/json:emit.into(buf: tgt.buf[tgt.head_pad..], value: { posts: ps }): n |> orisha:respond-filled(req, status: 200, tgt, n, ...): r

emit.ln

comptimetransform <scratch@scoped> koru_std/json.emitln.kz:35

emit.into

comptimetransform koru_std/json.emitln.kz:41

~part parsehelpers koru_std/json.parsehelpers.kz

Koru Standard Library: JSON — parse helpers. Joined via `~part helpers` in json.parse.kz; merged into the json.parse module at load. Holds the transform's helper container so the driver stays under the line wall.

~part parsesub koru_std/json.parsesub.kz

Koru Standard Library: JSON parse — sub-entry expansion. Joined via `~part sub` in json.parse.kz; merged into the json.parse module at load. A `{...}` spec written inline in a plain-brace schema arrives as spec text, not a sub-destructure; expanding it here binds the object's LEAVES (`addr:{ city }` binds `city`, not `addr`) — the same shape the sub-destructure form produces.

~part dom koru_std/json.dom.kz

Koru Standard Library: the `dom` part of json.kz — a runtime JSON document model. Joined via `~part dom` in json.kz; merged into the module at load. The navigation twin of `std/json:parse`'s schema-directed transform: where `parse` compiles the `ok` destructure into a bespoke typed reader (schema fixed at compile time, no tree ever built), `dom` materializes the whole document — for consumers whose access paths are not known at compile time (jq-shaped tools, generic walkers, recursive descent over arbitrary input). The node type is Zig's std.json.Value over a parseFromSlice arena: `Document` owns the arena (one `<open!>` obligation, discharged only by `dom.free`); every `*JsonNode` handed out by `root`/`at`/`idx`/`each` borrows into it — valid while the Document lives, untracked (the same contract `std/string:split`'s `! piece` views draw, one level down). `dom.parse` copies every string into the arena (parseFromSlice's alloc_always for Value), so the input text is freeable immediately — nodes never point into it. `dom.render` mints `string<emitted!>` — discharged by the existing `std/json:emit.free`, same contract the emit transform writes against.

dom.parse

<*><open!> koru_std/json.dom.kz:29

dom.root

<open> koru_std/json.dom.kz:34

dom.free

<!open> koru_std/json.dom.kz:38

dom.render

<*><emitted!> koru_std/json.dom.kz:82

~part gets koru_std/json.gets.kz

Koru Standard Library: JSON — value getters. Joined via `~part gets` in json.kz; merged into the json module at load. Split out of json.kz to keep it under its line pin. Decoding - Extract values from JSON strings

~part helpers koru_std/json.helpers.kz

Koru Standard Library: JSON — module helpers. Joined via `~part helpers` in json.kz; merged into the json module at load. Shared writers used by the object/array builders in json.kz. Helpers