radlang — JSON (json)
This document covers the json namespace: parsing and serializing JSON. JSON
is read recursively into a type you declare (json.parse<T>). Use declared DTOs
for known object shapes and map[string,V] for genuinely dynamic keys whose
values share a declared type. The legacy uppercase Map remains string-valued.
For language fundamentals see the Overview.
Overview
json is a compiler-intrinsic namespace. The name is reserved and
dispatched directly to the runtime — it needs no import:
type Person {
string name,
int age
}
fn main() {
Person p = Person("Ada", 36)
string encoded = json.from(p) // {"name":"Ada","age":36}
Person back = json.parse<Person>(encoded)
sys.output(back.name) // Ada
}radlang structs and lists convert to and from JSON automatically through
json.parse<T> and json.from.
JsonNodeis internal. The parsed-tree type behind the parser is not part of the language: namingJsonNode, callingjson.parse(s)without a type argument, or using the old navigation calls (json.get,json.at,json.getString,json.keys,json.stringify, …) is a compile error. Declare a type for the JSON, or usejson.parse<Map>(below).
Serializing — json.from
json.from(value) : stringConverts a radlang value to a JSON string. It handles primitives, null,
lists, structs (including nested structs and lists of structs), any, and
union types.
type Person {
string name,
int age,
bool is_student
}
fn main() {
sys.output(json.from(42)) // 42
sys.output(json.from("hi")) // "hi"
sys.output(json.from(true)) // true
sys.output(json.from([1, 2, 3])) // [1,2,3]
Person p = Person("Tim", 30, true)
sys.output(json.from(p)) // {"name":"Tim","age":30,"is_student":true}
}A struct with no fields serializes as the empty object {}, at the root and
nested (a field of an empty struct type is written as {}). A partial struct
(?T) writes only the fields that were supplied. json.from writes floats with
six significant digits: [0.123457,1] for [0.12345678901234567, 1.0]. A
Map encodes as an object whose values are all strings, and a map[string,V]
as an object of typed values.
Exact floats — json.fromExact
For checkpoints and other exact numeric data, use json.fromExact(value).
It follows the same typed traversal, including nested/nullable values, and
formats finite f64 values with shortest round-trip decimals. Parsing back into
the same type preserves those values, including negative zero. Non-finite
floats serialize as JSON null; JSON cannot represent NaN or infinities.
json.from retains its existing six-significant-digit float presentation, and
writes a non-finite float as nan or inf, which is not valid JSON.
float[] weights = [0.12345678901234567, 1.0000000000000002]
float[] restored = json.parse<float[]>(json.fromExact(weights)) Per-call parser limits
json.parse<T>(text, limits) accepts an optional struct with exactly these
four integer fields (int, uint, or long), in any declaration order:
var limits = {
maxInputBytes: 67108864,
maxAllocatedBytes: 268435456,
maxDepth: 256,
maxItems: 2097152
}
Checkpoint restored = json.parse<Checkpoint>(text, limits)All limits must be positive and fit addressable storage. The input limit counts
bytes. The allocation budget counts parser allocations, including alignment and
abandoned growth buffers; it does not bound all application memory or subsequent
typed conversion. Depth counts nested containers. Items limit each container’s
members/elements, independently of its backing capacity. Choose limits suitable
for the input’s trust and expected size. Invalid options or exceeded limits
throw a catchable Error, and partial parser allocations are reclaimed.
Omitting limits preserves the defaults: 16 MiB input, 64 MiB parser allocation,
128 levels, and 1,048,576 items per container. Overrides belong to that call;
they do not change HTTP controller parsing or another coroutine’s defaults.
XML accepts the same options; see XML.
Typed parsing — json.parse<T>
json.parse<T>(s: string) : T // deserialize into T
json.valid(s: string) : bool // is s well-formed JSON (never throws)json.parse<T> deserializes into a primitive, a struct, a list, a declared union,
a typed string-keyed dictionary, or a Map —
including nested structures. It throws on malformed JSON; check with
json.valid(s) first when the input may be bad.
Typed parsing also checks supplied values before conversion. A string field
requires a JSON string, a boolean requires a JSON boolean, and numeric fields
require JSON numbers. Integer targets require an integral value within the
target’s range. Integral decimal/exponent forms such as 12.0 and 1.2e1 are
accepted; fractions, numeric strings, booleans and out-of-range integers throw
catchable errors. Checks recurse through declared DTOs, lists and nullable fields.
There is no separate parse method or validation-mode option.
Missing fields keep their existing defaults; nullable fields remain null when
missing or explicitly null. Supplied nulls require nullable targets. Partial
structs retain their field-presence masks. Additional object keys are ignored.
Required-field rules and application-specific ranges still belong to the caller.
Int(1.5) remains a numeric conversion; json.parse<int>("1.5") rejects a
fractional JSON value. json.valid checks JSON syntax, not a DTO’s shape.
Map behavior is unchanged: string members are raw text, other members are JSON text, and non-object roots produce an empty map. Declare nested types for complex known shapes instead of using Map as a substitute for typed JSON fields.
type Person {
string name,
int age,
bool is_student
}
type Group {
string group_name,
Person[] members
}
fn main() {
// Primitives
int n = json.parse<int>("42")
bool b = json.parse<bool>("true")
// Struct
Person p = json.parse<Person>('{"name":"Ada","age":36,"is_student":false}')
sys.output(p.name) // Ada
// Nested struct with a list of structs
string data = json.from(Group("Devs", [Person("Tim", 30, true)]))
Group g = json.parse<Group>(data)
sys.output(g.members[0].name) // Tim
}Supported type arguments: int, uint, long, float, bool, string,
char, byte, Map, any struct type, and lists of those.
Optional keys — nullable fields
A key that may be missing (or null) maps to a nullable field; it is null
when absent:
type Claims {
string sub,
int? exp,
string? role
}
fn main() {
Claims c = json.parse<Claims>('{"sub":"ada","exp":1700000000}')
string role = c.role ?? "user" // "user": no role key
int exp = c.exp ?? 0
} Declared unions and recursive dictionaries
Use declared types for complex shapes. Parsing and serialization recurse through their fields, lists, dictionaries and unions; no additional parse API is needed.
type ContentPart { string type, string? text }
type Content = string | ContentPart[]
type Message { string role, Content? content }
type Additional = bool | Schema
type Schema {
string? type,
map[string,Schema]? properties,
Additional? additionalProperties,
[json("$ref")] string? ref,
[json("$defs")] map[string,Schema]? defs
}Unions select variants by JSON kind: boolean, string, array, object or null.
One integer and one floating-point variant may coexist: integer tokens select
the integer variant when in range; fractional tokens and other finite numbers
select the floating-point variant. Without a floating variant, integral decimal
tokens are accepted by the integer variant. Same-kind alternatives such as
int[] | string[] or two object DTOs are ambiguous and fail compilation, including
when nested in imported, generic or recursive DTOs. Mismatched input throws a
catchable error. Nonnullable union fields must be supplied.
map[string,V] stores native typed values, including recursive DTOs and unions.
Its methods are get(string): V, has(string): bool, keys(): string[],
size(): int, set(string,V) (returns the dictionary), and remove(string).
Missing get keys throw a catchable error; use has before optional access.
Iteration uses for (string key in dictionary.keys()). Default declarations
create an empty dictionary. JSON roots must be objects and every value is checked
against V. Non-string keys and bracket indexing are compile errors. Uppercase
Map retains its separate string-valued behavior.
Declared singleton aliases of dictionaries use the same methods and convert
through their native dictionary representation in fields, returns and ??
fallbacks. Storage is invariant: an integer dictionary cannot be reinterpreted
as a floating-point dictionary. A null nullable receiver throws; safe mode also
requires an explicit null check before calling a nullable dictionary method.
Keys and JSON members retain insertion order; replacing a key preserves its
position, and a removed then reinserted key appends at the end.
[json("wire-name")] maps a DTO field to a JSON key for both parsing and
serialization, including $ref and $defs. It changes neither the field’s
language name nor its layout. Duplicate wire names are compile errors. Aliases
survive source-less .rlc/.rlp imports; rebuild libraries to export them.
One [jsonExtra] map[string,V] extras field can capture unknown object members
as declared typed values. It has no own wire key: serialization flattens its
entries into the object. Declared fields and aliases take precedence over
same-name extra entries. This preserves extension fields and runtime reference
targets such as {"$ref":"#/custom","custom":{"type":"boolean"}} without
changing keys inside string values. The catchall value type is checked recursively
like any other dictionary; other DTOs continue ignoring unknown keys.
A nullable field whose union explicitly admits null distinguishes absence
from supplied null. For type Value = string | null, Value? const is absent
for a missing key, but present with the null variant for "const": null.
Serialization omits that outer-absent field and preserves supplied null. Ordinary
nullable fields retain their existing missing/null behavior. Recursive value
unions may combine scalar, list and typed dictionary variants without JsonNode.
Singleton aliases of lists also support native list methods, indexing and iteration while retaining their existing tagged storage. Existing implicit union-to-member assignments check the active variant before converting it; an incompatible active variant throws instead of becoming an invalid pointer. Union-to-union conversions preserve values even when variant order differs.
Objects with unknown keys — json.parse<Map>
When an object’s keys aren’t known in advance (JWT claims, a webhook payload,
a model’s tool-call arguments), parse it into a Map. Each member becomes a
string:
- a JSON string member is its text (
"ada"→ada); - any other member is its JSON (
42,true,null,[1,2],{"a":1}), which you can parse again withjson.parse<T>orjson.parse<Map>.
A missing key reads as "" (m.has(key) tells them apart). Anything other
than an object parses to an empty map.
fn main() {
Map m = json.parse<Map>('{"name":"Alice","age":28,"tags":["a","b"],"geo":{"lat":1.5}}')
string name = m.get("name") // Alice
int age = json.parse<int>(m.get("age")) // 28
string[] tags = json.parse<string[]>(m.get("tags"))
Map geo = json.parse<Map>(m.get("geo"))
float lat = json.parse<float>(geo.get("lat")) // 1.5
for (string key in m.keys()) {
sys.output(key) // name, age, tags, geo
}
}json.from encodes a Map the way it encodes a map[string, string]: an
object in insertion order whose values are all JSON strings, at the top level,
as a struct field or as a list element. Because a parsed Map keeps non-string
members as their JSON text, they come back as strings:
Map m = Map()
m.set("a", "1").set("b", 'x"y')
json.from(m) // {"a":"1","b":"x\"y"}
json.from(json.parse<Map>('{"n":12,"ok":true}')) // {"n":"12","ok":"true"}Use a typed record or map[string, T] when values must keep their JSON types.
Quick reference
| Call | Returns | Purpose |
|---|---|---|
json.from(value) |
string | Serialize any value to JSON |
json.fromExact(value) |
string | Serialize with exact (shortest round-trip) floats |
json.parse<T>(s) |
T | Deserialize into a primitive/struct/list |
json.parse<T>(s, limits) |
T | Same, with per-call input, allocation, depth and item limits |
json.parse<Map>(s) |
Map | An object’s members as strings |
json.valid(s) |
bool | Is s well-formed JSON |
Picking the right tool
- Producing JSON from your data →
json.from. - Consuming JSON of a known shape →
json.parse<T>into a struct; nullable fields for optional keys. - Consuming an object with unknown keys →
json.parse<Map>, thenjson.parse<T>on any member that is itself JSON. - Parsing a union → declare distinct JSON-kind variants and use
json.parse<T>. - Consuming dynamic keys with known value shapes →
map[string,V]in a DTO.