Module
std.json — the JSON data model, its accessors, and the serializer. Stability tier: core.
The module is a READER now, and that is this sprint's whole story. For eight sprints this was a complete DOM that could not be built from text: parse and unescape were reviewed contracts, and escape carried a refusal. §14's debt clause — a contract ships in the sprint AFTER its blocker closes, one sprint of grace and no more — came due here on all three at once, and all three are below as code.
- **parse** was blocked by F-0037 (an enum returned through an error row took the miss path on every call), closed at lupin 0.1.10 and spent at sc13 on get/at. Its scanner has been writable since sc09; the SIGNATURE was what was missing. - **unescape** was blocked by F-0057 — the walk was always fine, the walk's OUTPUT was not, because decoding é means building "é" out of the number 233 and nothing in the language built a str from a number. s81 landed the prelude's validating str_from_utf8, and lupin 0.1.12 resolves it too (F-0075 closed), which matters more here than anywhere: the interpreter is this module's only executing lane, so a primitive the compilers alone had would have left unescape with no lane at all (sc10's float_at rule). - **escape is TOTAL** and its boundary tag is gone. The walk is a byte walk now: the four characters JSON must escape are ASCII, every byte of a multi-byte code point is ≥ 0x80 and therefore never one of them, and a run between two escapes is a slice at offsets this module computed. So the function needs no code-point measurement at all — which is why it was reachable a full wave before anyone thought.
The signature change that follows, said out loud. escape's row disappears, so stringify and stringify_pretty go from {boundary, deep} to {deep} and quote becomes total. Every caller that wrote else "?" still compiles — a narrower row is a subtype at a ? boundary and an else over one tag reads the same — but a caller matching on boundary by name does not, and there is no deprecation period in a library at this stage. It is one tag, removed once, in the sprint that made it removable.
**What parse costs the reader is one number-tier tag**, and the sc05 contract did not have it: the row is {syntax, deep, overflow} rather than {syntax, deep}. overflow is what a magnitude with no f64 raises (1e400), because std.fmt.decimal.parse_float refuses it rather than answering infinity, and this module refuses to turn that into "the text is not JSON" — the two are different sentences and §12 gives a distinct actionable failure its own tag. RFC 8259 §6 permits an implementation to limit the range it accepts; it does not permit a parser to lie about which document it was handed.
The value model. Value is one recursive enum with seven variants: Null, Bool(bool), Int(int), Num(f64), Str(str), Arr(List[Value]) and Obj(Map[str, Value]). The number posture is the sprint contract's: integers keep their exactness in Int and only non-integral (or out-of-range) numbers become Num, so a document carrying a 64-bit id round-trips through wolf without passing through a f64 that cannot hold it. The i53 boundary is where the two postures visibly differ and tests/json/number_posture_and_depth.lu pins it, from the writing side, with tests/json/parse_shapes.lu pinning the reading side.
**Constructors are functions, not Value.Int(3).** An enum's variants cannot be named from outside the declaring module at these pins — json.Value.Int(3) is "Value is an enum; traits, enums and type-level items have no dynamic semantics here" (F-0029) — so the seven from_*/null constructors below exist to give importers any way at all to build a value. They are not the API the contract imagined; they are the API the language currently allows, and the filing says so.
Ordering. Obj is a Map, whose iteration order is unspecified (§8), so stringify's key order is unspecified too and no test in this repo asserts it for a multi-key object. That is a promise deliberately not made rather than an omission; when the ordering question settles upstream, this module states whatever the answer is.
Every lane runs this module (wolf 0.2.35, sc72; wolf-std#93). From sc05 to sc71 this paragraph said the wolfc lane was dark here by construction — an imported module that produces an enum value was unsupported on the checked tier with no recorded type natively (F-0029, F-0012), and Map was untyped. Neither half is true now. The checked machine has run six of the nine tests/json/ files since the sc44 and sc46 pins ([type.map] typed the DOM; wolf-lang#337's casts convert), and from wolf 0.2.35 the native rung runs all nine: Value's payload slots disagree (Bool(bool), Int(int), Num(f64), Str(str), Arr(…), Obj(…)), and s257's spilled union ([abi.native.enum]) gives each conflicting slot a union where the rung used to refuse the layout. lupin runs all nine, as it always has. Three of the nine end exit(1) by design on every lane that runs them (navigation_rows, parse_misses, unescape_shapes: the error row reaching main is the assertion). The checked machine still stops on three (number_posture_and_depth, parse_misses and pretty_and_escape: its call-depth budget twice and a tag pattern in checked execution, wolf-lang#882), so their wolfc cells stay unsupported.
**The scanner's tag is syntax, not parse, and the reason is a measurement rather than a preference.** A row tag is resolved as an ordinary name at the raise site, so a tag that shares a name with anything in scope silently becomes that thing (F-0036). This module now declares pub fn parse, so a parse TAG raised anywhere in it would resolve to that function and ride out as a value with no else firing and no diagnostic. Re-measured at this sprint's pins rather than inherited: the compiler closed its half at sc07 and lupin still hands back the colliding thing, silently. So unescape raises syntax too, which reads better anyway — a bad \q escape IS a syntax error in the document it came from.
What is deliberately NOT accepted. No comments, no trailing commas, no leading +, no bare .5, no NaN/Infinity spellings, no raw control character inside a string: RFC 8259's grammar, strictly. Every one of them is a syntax miss, because a library that guesses at extensions reads a different language from the one its callers' other tools read. There is also no offset in the tag — syntax is a payload-free mark until §12's payload conventions reach this module, and when the position arrives the tag GAINS a payload rather than a sibling (§12's rule 4).
Duplicate keys keep the last occurrence, which is a Map assignment and not a policy this module implements; a document with duplicate keys is legal and its readings differ across libraries, so the rule is stated here and held as a test rather than left to be inferred from the container. It is also the language's ruled reading (ruling #61, wolf-lang [os.json.dup]): a JSON object is a map, one member per name, at the position of its first appearance, holding its last value, and len counts names. std.x.json's kernels read the same text the same way from wolf 0.2.27 / lupin 0.1.50 on; before that they answered the first occurrence and counted every repeat.
Functions and methods
fn · Source line 162
pub fn depth_limit() -> int
The nesting depth this module reads and renders before raising deep — one number for parse, stringify and stringify_pretty, so a value that came in can always go back out.
A limit rather than a stack overflow, in BOTH directions and for the same reason: a JSON value can be built to any depth by a program and a document can be nested to any depth by whoever sent it, and there is no unwinding in wolf (D30), so a library that recurses until the stack ends hands its caller a denial-of-service surface rather than a function. parse was the sprint contract's example of the rule; stringify shipped it first because it shipped first.
json.depth_limit() == 64
fn · Source line 171
pub fn null() -> Value
The JSON null.
json.is_null(json.null()) == true
fn · Source line 181
pub fn from_bool(b: bool) -> Value
A JSON boolean.
(json.as_bool(json.from_bool(true)) else false) == true
json.type_name(json.from_bool(false)) == "bool"
fn · Source line 193
pub fn from_int(n: int) -> Value
A JSON number that is an integer, kept exact — the posture the module header describes. from_int(9007199254740993) survives a round trip through this model; the same value through from_num does not.
(json.as_int(json.from_int(42)) else 0) == 42
json.type_name(json.from_int(42)) == "int"
fn · Source line 205
pub fn from_num(x: f64) -> Value
A JSON number that is not (or need not be) an integer. Non-finite inputs are legal here and render as null, because JSON has no spelling for them — see stringify.
(json.as_float(json.from_num(1.5)) else 0.0) == 1.5
json.type_name(json.from_num(1.5)) == "num"
fn · Source line 217
pub fn from_str(s: str) -> Value
A JSON string. The text is stored as given; escaping happens at stringify time and never here, so a value that came from a program is never double-escaped.
(json.as_str(json.from_str("wolf")) else "?") == "wolf"
json.type_name(json.from_str("")) == "str"
fn · Source line 229
pub fn from_list(xs: List[Value]) -> Value
A JSON array over an already-built list of values.
var xs = List[json.Value]()
(mut xs).push(json.from_int(1))
let arr = json.from_list(xs)
(json.len(arr) else 0) == 1
fn · Source line 242
pub fn from_map(m: Map[str, Value]) -> Value
A JSON object over an already-built map. The map's iteration order is unspecified and so is the rendered key order (§8).
var m = Map[str, json.Value]()
m["a"] = json.from_int(1)
let obj = json.from_map(m)
json.type_name(obj) == "obj"
fn · Source line 263
pub fn type_name(v: Value) -> str
The variant's name — "null", "bool", "int", "num", "str", "arr" or "obj". The one accessor that never fails, and the one a diagnostic wants: the kind row tag says a value was the wrong shape, and this says which shape it was. Total: no error row, no traps.
Spelled type_name and not kind, which is what it would be called in any other library: a function and a row tag with the same name in one module make the tag resolve to the FUNCTION at the raise site — silently, so as_int(json.null()) yielded a function value instead of raising, and else never fired (F-0036). "int" and "num" are not RFC 8259 type names; they are this model's, and the header explains why the number split exists.
json.type_name(json.null()) == "null"
json.type_name(json.from_str("x")) == "str"
fn · Source line 282
pub fn is_null(v: Value) -> bool
Whether v is the JSON null. A predicate rather than a row, because "is it null" is a question with a boolean answer (§1). Total.
json.is_null(json.null()) == true
json.is_null(json.from_int(0)) == false
fn · Source line 298
pub fn as_bool(v: Value) -> bool ! {kind}
The boolean v holds; kind when it holds something else. No coercion: as_bool of Int(0) is a miss, not false, because JSON's types are the document's and guessing across them is how a parser loses data.
(json.as_bool(json.from_bool(true)) else false) == true
(json.as_bool(json.from_int(1)) else false) == false
fn · Source line 314
pub fn as_int(v: Value) -> int ! {kind}
The integer v holds; kind for every other variant, Num included. A Num that happens to be integral is still not an Int: the model records which one the document had, and as_float is the widening direction that always works.
(json.as_int(json.from_int(42)) else 0) == 42
(json.as_int(json.from_num(42.0)) else 0) == 0
fn · Source line 342
pub fn as_float(v: Value) -> f64 ! {kind}
The number v holds as f64; kind for every non-numeric variant. This one DOES widen: an Int converts, because every JSON number is a number and a caller asking for f64 has said it accepts the rounding. Beyond 2^53 that rounding is lossy, which is exactly why as_int exists and does not do it.
The Int line of the fence below was PROSE from sc44 to sc46, for a filed compiler bug rather than anything about this function: on the checked tier a value produced by int as f64 compared unequal to every f64 it was numerically equal to — (3 as f64) == 3.0 was false there and true on the native rung and under lupin, at v0.2.10 and v0.2.11 alike (wolf-lang#337). It was a green fence that started failing at a pin bump and never a claim that was wrong. wolf-lang#337 closed in v0.2.12 and the line is back where it started, measured here at 0.2.12/0.1.34 on all three lanes.
(json.as_float(json.from_int(3)) else 0.0) == 3.0
(json.as_float(json.from_num(1.5)) else 0.0) == 1.5
(json.as_float(json.from_str("3")) else 0.0) == 0.0
fn · Source line 357
pub fn as_str(v: Value) -> str ! {kind}
The string v holds, unescaped (the model stores text, not JSON source); kind otherwise.
(json.as_str(json.from_str("wolf")) else "?") == "wolf"
(json.as_str(json.null()) else "?") == "?"
fn · Source line 374
pub fn as_arr(v: Value) -> List[Value] ! {kind}
The array v holds; kind otherwise. The list is the value's own — reading it is free, and this module never hands out a copy it did not have to make.
var xs = List[json.Value]()
(mut xs).push(json.null())
let got = json.as_arr(json.from_list(xs)) else List[json.Value]()
got.len == 1
fn · Source line 389
pub fn as_obj(v: Value) -> Map[str, Value] ! {kind}
The object v holds; kind otherwise.
var m = Map[str, json.Value]()
m["k"] = json.from_int(1)
let got = json.as_obj(json.from_map(m)) else Map[str, json.Value]()
got.len == 1
fn · Source line 414
pub fn has(v: Value, key: str) -> bool
Whether v is an object with an entry at key. false for every other variant, because "does this document have this field" has a useful answer for a non-object too, and it is no.
It survives get's arrival rather than being replaced by it, and the reason is §1's: a question with a boolean answer keeps its predicate. has is what a caller writes when the value is not wanted (a schema check, a "did this field appear at all" branch over a null that IS present); get is what a caller writes when it is.
var m = Map[str, json.Value]()
m["a"] = json.from_int(7)
let obj = json.from_map(m)
json.has(obj, "a") == true
json.has(obj, "b") == false
json.has(json.from_int(1), "a") == false
fn · Source line 472
pub fn get(v: Value, key: str) -> Value ! {kind, none}
The value at key; none when the object has no entry there, kind when v is not an object at all.
Two tags rather than one, because the two questions are different. "This document has no port field" is a thing a caller routinely plans for; "the thing you are indexing is a number" is a caller's mistake about its own data — and §12 keeps them apart so an else can too. A caller that genuinely does not care writes else json.null().
Bare get with a row is §1's checked-access spelling. There is no get_ prefix and no unchecked twin: an absent key is not a fault (§8), so the trapping direction this function could have had does not exist and never will.
**This function and at were written at sc05, tested, and withdrawn for five sprints** — a Value returned through an error row took the miss path on every call, silently (F-0037, closed at lupin 0.1.10 and re-measured at 0.1.11 and again at 0.1.12). Nothing about the signature changed in the meantime, which is the point: the contract in the module header was right, and what was missing was a machine that ran it.
var m = Map[str, json.Value]()
m["a"] = json.from_int(7)
m["n"] = json.null()
let obj = json.from_map(m)
let a = json.get(obj, "a") else json.from_int(0 - 1)
(json.as_int(a) else 0) == 7
let missing = json.get(obj, "zz") else json.from_str("absent")
(json.as_str(missing) else "?") == "absent"
let n = json.get(obj, "n") else json.from_int(0 - 1)
json.is_null(n) == true
let wrong = json.get(json.from_int(1), "a") else json.from_str("not an object")
(json.as_str(wrong) else "?") == "not an object"
fn · Source line 521
pub fn at(v: Value, i: int) -> Value ! {kind, none}
The element at i; none when i is outside the array, kind when v is not an array.
**A row where List traps** (§8, and this is the worked example of its rule): an index into a document is DATA — the caller could not have checked what the document contains, because reading the document is what it is doing — so an out-of-range index is an outcome this function reports and never a process this function ends. A negative index is the same miss and not a from-the-end read; ^n does not exist in wolf and inventing it here would be a second dialect.
Withdrawn with get at sc05 and shipped with it now; see get.
var xs = List[json.Value]()
(mut xs).push(json.from_str("first"))
(mut xs).push(json.null())
let arr = json.from_list(xs)
let a = json.at(arr, 0) else json.from_str("?")
(json.as_str(a) else "?") == "first"
let past = json.at(arr, 2) else json.from_str("past the end")
(json.as_str(past) else "?") == "past the end"
let below = json.at(arr, 0 - 1) else json.from_str("below zero")
(json.as_str(below) else "?") == "below zero"
let wrong = json.at(json.from_int(1), 0) else json.from_str("not an array")
(json.as_str(wrong) else "?") == "not an array"
fn · Source line 550
pub fn keys(v: Value) -> List[str] ! {kind}
The keys of an object, in the map's unspecified order; kind for every other variant. Allocates the list (to_-grade, §1).
var m = Map[str, json.Value]()
m["only"] = json.null()
let ks = json.keys(json.from_map(m)) else List[str]()
ks.len == 1
let none_here = json.keys(json.from_int(1)) else List[str]()
none_here.len == 0
fn · Source line 577
pub fn len(v: Value) -> int ! {kind}
The number of elements in an array or entries in an object; kind for every scalar. Not a string length: JSON strings are text and std.str.len is where text length lives.
var xs = List[json.Value]()
(mut xs).push(json.null())
(mut xs).push(json.null())
(json.len(json.from_list(xs)) else 0) == 2
(json.len(json.from_int(1)) else 0 - 1) == 0 - 1
fn · Source line 620
pub fn parse(s: str) -> Value ! {syntax, deep, overflow}
s parsed as one JSON document — the direction this module could not go for eight sprints.
The profile is RFC 8259, strictly, and the module header lists what that excludes. Whitespace (space, tab, CR, LF) is allowed around every token and nowhere inside one; trailing content after the value is a miss, so "1 2" does not parse as 1.
Numbers keep the posture the model was built for: text that denotes an integer int can hold becomes Int and keeps every digit, and everything else becomes Num through std.fmt.decimal.parse_float, which is correctly rounded. So a document carrying a 64-bit id survives a round trip and 1e2 arrives as the double 100.0 rather than as the integer 100 — the text said it was not an integer.
Three tags. syntax is a malformed document. deep is nesting past depth_limit(), raised rather than recursing until the stack ends: an untrusted document must not be able to end the process, which is the same argument stringify makes from the writing side. overflow is a number whose magnitude has no f64 (1e400) — the number tier refuses it rather than answering infinity, and this module refuses to call that a malformed document.
A duplicate key keeps the LAST occurrence.
let v = json.parse("[1, true, null]") else json.null()
(json.len(v) else 0) == 3
let n = json.parse(" 42 ") else json.null()
(json.as_int(n) else 0) == 42
let s = json.parse("\"a\\nb\"") else json.null()
(json.as_str(s) else "?") == "a\nb"
let bad = json.parse("[1,]") else json.from_str("not json")
(json.as_str(bad) else "?") == "not json"
fn · Source line 1015
pub fn escape(s: str) -> str
s with the characters JSON forbids inside a string replaced by their escapes: " and \ by their backslash forms, and every control character below U+0020 by \b, \f, \n, \r, \t or \u00XX. Every other character — including every non-ASCII one — passes through verbatim, because RFC 8259 permits raw UTF-8 and escaping it would only make the output bigger.
**Total, as of sc14, and its boundary tag is gone.** For five sprints this function refused a string that held a non-ASCII code point AND, after it, a character needing an escape: the walk stepped one ASCII character at a time and nothing could measure a wider one. What removed the refusal is not the code-point primitive the old contract named but a change of QUESTION. The four characters that must be escaped are ASCII; every byte of a multi-byte code point is ≥ 0x80 and so is never one of them; a run between two escapes is therefore a slice at two offsets THIS function computed, and a byte walk needs no code-point measurement at all. The old body was answering a harder question than the job asked.
The removal is a signature change and the module header says so: stringify and stringify_pretty lose boundary from their rows.
A string needing no escape at all comes back unchanged, and the fast path is the walk finding nothing rather than a second pass.
json.escape("wolf") == "wolf"
json.escape("café") == "café"
json.escape("café \"x\"") == "café \\\"x\\\""
json.escape("a\"b") == "a\\\"b"
json.escape("a\\b") == "a\\\\b"
json.escape("a\nb") == "a\\nb"
fn · Source line 1083
pub fn unescape(s: str) -> str ! {syntax}
s with JSON's escapes resolved — escape's inverse, and the function parse reads every string payload through.
The eight two-character escapes (\", \\, \/, \b, \f, \n, \r, \t) and \uXXXX, with a surrogate PAIR joined into the one code point it denotes. Any other character after a backslash is a syntax miss, and so is a lone surrogate, a truncated \u, and a trailing backslash. Text with no backslash in it comes back unchanged.
**The tag is syntax and not the parse its sc05 contract named**, because this module now has a FUNCTION called parse and a row tag that shares a name with anything in scope resolves to that thing — silently, with no else firing and no diagnostic (F-0036, re-measured under lupin at this sprint's pins and still live there). The rename is also the better name.
What it waited four sprints for. Decoding é means building "é" out of the number 233, and nothing in the language built a str from a number until s81's validating str_from_utf8 (F-0057, closed at the sc13 pin, wrapped as std.bytes.to_str). An ASCII-only version would have refused text, which §9 forbids.
(json.unescape("wolf") else "?") == "wolf"
(json.unescape("a\\nb") else "?") == "a\nb"
(json.unescape("a\\\"b") else "?") == "a\"b"
(json.unescape("\\u00e9") else "?") == "é"
(json.unescape("\\ud83d\\udc3a") else "?") == "🐺"
(json.unescape("a\\qb") else "bad escape") == "bad escape"
(json.unescape("\\ud800") else "lone surrogate") == "lone surrogate"
fn · Source line 1281
pub fn stringify(v: Value) -> str ! {deep}
v rendered as compact JSON text — no spaces, no newlines, keys in the map's unspecified order. One tag: deep, when nesting passes depth_limit(). It used to be two — boundary left with sc14's total escape, and a caller that named that tag is the one call site this module's history breaks.
Numbers: an Int renders as a decimal integer, exactly; a Num renders through std.fmt.decimal.to_str, the shortest text that reads back as the same double — so stringify of a document a program built loses nothing. A non-finite Num renders as null, because JSON has no spelling for infinity or NaN and the alternative (a raise, or inventing 1e999) is worse for the caller and worse for the reader; JavaScript's own JSON.stringify made the same choice.
(json.stringify(json.null()) else "?") == "null"
(json.stringify(json.from_bool(true)) else "?") == "true"
(json.stringify(json.from_int(42)) else "?") == "42"
(json.stringify(json.from_num(1.5)) else "?") == "1.5"
(json.stringify(json.from_str("hi")) else "?") == "\"hi\""
var xs = List[json.Value]()
(mut xs).push(json.from_int(1))
(mut xs).push(json.null())
(json.stringify(json.from_list(xs)) else "?") == "[1,null]"
fn · Source line 1300
pub fn stringify_pretty(v: Value, indent: int) -> str ! {deep}
v rendered as JSON text with indent spaces per nesting level and one entry per line — the human-readable form. An indent of zero gives newlines without indentation; a negative indent traps assert. Empty arrays and objects stay on one line ([], {}), which is what every pretty-printer does and what every diff wants. The rows are stringify's.
(json.stringify_pretty(json.from_int(1), 2) else "?") == "1"
var xs = List[json.Value]()
(mut xs).push(json.from_int(1))
(json.stringify_pretty(json.from_list(xs), 2) else "?") == "[\n 1\n]"
var empty = List[json.Value]()
(json.stringify_pretty(json.from_list(empty), 2) else "?") == "[]"