JSON
abla/json provides one phase-safe JSON data model for runtime parsing, compile-time evaluation, and $json literals. It has no HTTP or host-runtime dependency.
import "abla/io"
import "abla/json"
fun main {
val parsed = jsonParse("{\"name\":\"Abla\",\"versions\":[1,2.5e1]}")
if (parsed.succeeded) {
println(parsed.value.get("name").asString())
println("${parsed.value.get("versions").size()} versions")
println(jsonStringify(parsed.value))
}
}
// output:
// Abla
// 2 versions
// {"name":"Abla","versions":[1,2.5e1]}
Decoding with a typed outcome
jsonParse answers with a JsonParseResult whose value is JSON null when the input is bad, so a caller that skips succeeded reads a null. jsonDecode answers with a sealed JsonDecoded, and a when over it has to say what each case does (a case left out is when.non-exhaustive):
| Case | When | Fields |
|---|---|---|
JsonParsed | one JSON value within the limits | value: Json |
JsonMalformed | not JSON, or against a rule the limits don't govern: unexpected_token, unexpected_end, invalid_number, trailing_input, invalid_unicode, duplicate_key | error: JsonError |
JsonLimitExceeded | more than JsonLimits allow, however well formed: input_limit, node_limit, depth_limit | error: JsonError |
import "abla/io"
import "abla/json"
fun describe(source: string): string {
val decoded = jsonDecode(source)
return when (decoded) {
is JsonParsed -> "a value of kind ${decoded.value.kind}"
is JsonMalformed -> "bad input: ${decoded.error.message}"
is JsonLimitExceeded -> "too large: ${decoded.error.message}"
}
}
fun main {
println(describe("[1,2]"))
println(describe("[1,"))
}
// output:
// a value of kind 4
// bad input: expected JSON value
The two failure cases carry the JsonError that jsonParse reports for the same input and limits (code, message, byte offset, line, column), so a server can answer 400 for malformed input and 413 for a limit. jsonDecodeDocument is the same for the tape document of jsonDocument (JsonParsedDocument, JsonMalformed, JsonLimitExceeded). jsonParse and jsonDocument stay.
Values and numbers
Json.kind has these stable values:
| Kind | Meaning |
|---|---|
0 | null |
1 | string |
2 | number |
3 | Boolean |
4 | array |
5 | object |
6 | raw: an already-encoded value (see Raw nodes); never produced by parsing |
All JSON numbers use one JsonNumber representation. Its text field keeps the validated source lexeme, so fractions, exponents, and integers larger than Abla's signed int are never rounded. integer is true only when the lexeme has neither a fraction nor an exponent. intAvailable reports whether the number fits an Abla int; intValue is meaningful only in that case.
The public constructors are jsonNull, jsonString, jsonNumber, jsonNumberText, jsonInteger, jsonBoolean, jsonArray, and jsonObject. jsonNumberText validates its argument. Invalid UTF-8 strings, invalid number text, and mismatched object key/value arrays produce the null sentinel rather than an invalid tree. Arrays passed to array and object constructors become the stored ordered children; normal Abla ownership rules apply to those values.
The kind predicates are isNull, isString, isNumber, isBoolean, isArray, and isObject. Accessors deliberately have simple sentinel behavior until the standard library has a generic result type:
asString()returns""for a non-string;asBoolean()returnsfalsefor a non-Boolean;asNumber()returns an unavailable empty number for a non-number;asInt()returns0unlessintAvailable()is true;get(key)returns JSON null when the key is absent;size()returns zero for scalar values; andat(index)uses the ordinary checked array-index behavior.
Use a kind predicate, has, or intAvailable when a sentinel could be ambiguous.
Strict parsing
import "abla/io"
import "abla/json"
fun main {
val result = jsonParse("{\"a\": 1,}")
if (!result.succeeded) {
val error = result.error
println("${error.code} at byte ${error.byteOffset}, line ${error.line} column ${error.column}")
}
}
// output:
// unexpected_token at byte 8, line 1 column 9
jsonParse accepts the standard JSON grammar and valid UTF-8. It rejects comments, trailing commas (which $json literals allow), leading plus signs, leading zeroes, incomplete fractions or exponents, unescaped control bytes, lone UTF-16 surrogates, duplicate object keys, and non-whitespace trailing input. Escaped surrogate pairs are decoded to UTF-8. Error offsets count source bytes; line and column are one-based.
On failure, succeeded is false, value is JSON null, and error.code is one of:
unexpected_endunexpected_tokentrailing_inputinvalid_escapeinvalid_unicodeinvalid_numberduplicate_keydepth_limitnode_limitstring_limitinput_limit
Error messages are diagnostic text and may improve; branch on the code.
If malformed input should be treated exactly like JSON null, use jsonParse(text).value directly. The parser already returns JSON null on failure, so there is no need to check succeeded and supply jsonNull() again. Use the full result when you must distinguish an invalid document from a successful parse of null, report an error, or choose a different fallback.
import "abla/io"
import "abla/json"
fun main {
println(jsonStringify(jsonParse("{\"a\":1}").value))
println(jsonStringify(jsonParse("null").value))
println(jsonStringify(jsonParse("{").value))
}
// output:
// {"a":1}
// null
// null
Every parse is bounded by JsonLimits. jsonDefaultLimits() returns jsonStandardLimits:
| Limit | Default |
|---|---|
| input bytes | 1 MiB |
| nesting depth | 64 |
| value nodes | 100,000 |
| decoded bytes per string | 1 MiB |
| members per object | 10,000 |
Each call's limits are its own: a caller parsing a large trusted document raises bytes, nodes, strings and members as far as it needs. Limits must be positive, and the depth at most 256, since parsing recurses per level; invalid limits return input_limit. Duplicate keys are rejected by default. Setting rejectDuplicateKeys to false preserves every member in source order; jsonStringify emits them in that order and get observes the last matching member. Setting mergeDuplicateKeys as well merges them as JavaScript's JSON.parse does: a key keeps its first position and takes its last value.
jsonPermissiveLimits reads what JSON.parse reads: no byte, node, string or member limit, nesting to depth 256, and duplicate keys merged:
import "abla/io"
import "abla/json"
fun main {
val parsed = jsonParse("{\"a\":1,\"b\":2,\"a\":3}", jsonPermissiveLimits)
println("${jsonStringify(parsed.value)} ${parsed.value.getInt("a")}")
}
// output:
// {"a":3,"b":2} 3
jsonValidate(source, limits) answers whether jsonParse would accept a document without building its tree: the same succeeded and error (code, message, offset, line and column) under the same limits, merging included, with a null value. It checks a large document at tens of megabytes a second, allocating only for strings with escapes and for the keys of objects whose duplicates are rejected or merged:
import "abla/io"
import "abla/json"
fun main {
val checked = jsonValidate("[1, 2, {\"a\": tru}]")
println("${checked.succeeded} ${checked.error.code} at ${checked.error.byteOffset}")
println("${jsonValidate("{\"a\":1,\"a\":2}", jsonPermissiveLimits).succeeded}")
}
// output:
// false unexpected_token at 13
// true
Documents: a parsed tree without the tree
jsonDocument(source, limits) parses as jsonParse does (the same succeeded and error, merging included) but keeps the document as its source and a tape of four integers per value instead of building Json nodes: a fraction of the memory, nothing for the collector to walk value by value, and several times faster on large documents. Its root() is a JsonNode, which reads like the tree:
kind(),isNull()…isObject(),size(),exists()(false for a
missing member or element, which reads as null);
at(index)(an element, or an object's member value),keyAt(index),
get(key), has(key), getString(key), getInt(key);
asString(),asNumber(),asInt(),intAvailable(),asBoolean(),
asF64() (a number as the nearest f64, as a reader's readNumber);
raw(): the value's source text exactly as written, a slice, not a copy;toJson(): theJsontreejsonParsebuilds for that value.
Members read as jsonParse's object holds them: with mergeDuplicateKeys a repeated key counts once, at its first position, with its last value; get gives the last value for a key either way. Strings with escapes are decoded when read.
import "abla/io"
import "abla/json"
fun main {
val parsed = jsonDocument("{\"name\":\"Abla\",\"versions\":[1, 2.5e1],\"name\":\"x\"}", jsonPermissiveLimits)
val root = parsed.document.root()
val versions = root.get("versions")
println("${root.size()} ${root.getString("name")} ${versions.size()} ${versions.at(1).raw()}")
println(jsonStringify(root.toJson()))
}
// output:
// 2 x 2 2.5e1
// {"name":"x","versions":[1,2.5e1]}
To go through every element or member, take a cursor: elements() on an array, members() on an object. next() steps to the next one, and the cursor reads the current one in place (kind(), size(), asString(), asInt(), asF64(), asNumber(), asBoolean(), raw(), utf16Length(), and for a member key() and keyIs(name), which compares without making a string): stepping and reading scalars allocate nothing. node() gives the current one as a JsonNode, and elements() / members() a cursor into it. Members come as jsonParse's object holds them. utf16Length() is a string's length in UTF-16 code units, as JavaScript counts it.
import "abla/io"
import "abla/json"
fun main {
val parsed = jsonDocument("[{\"id\":1,\"name\":\"a\\u00e9\"},{\"id\":2,\"name\":\"\\ud83d\\ude00\"}]")
var records = parsed.document.root().elements()
while (records.next()) {
var fields = records.members()
var line = ""
while (fields.next()) {
if (fields.keyIs("id")) line = "$line id ${fields.asInt()}"
else line = "$line ${fields.key()} ${fields.asString()} (${fields.utf16Length()})"
}
println(line)
}
}
// output:
// id 1 name aé (2)
// id 2 name 😀 (2)
To change a document and write it out, collect edits and emit: edits() starts a list; set(object, key, value) and delete(object, key) name an object node of the document, a key and (for set) a Json value; emit() writes the edited document in one pass. The result is exactly jsonStringify of jsonParse's tree with the edits applied (also available as edits.toJson()): compact, strings escaped as jsonStringify escapes them, numbers as written. Edits apply in order to the members as jsonParse's object holds them: set replaces the value of the last member with that key, or adds the member at the end; delete removes every member with that key. document.emit() writes the document unchanged (as jsonStringify(jsonParse(source).value)).
import "abla/io"
import "abla/json"
fun main {
val document = jsonDocument("[{\"id\": 1, \"note\": \"x\"}, {\"id\": 2}]").document
var edits = document.edits()
var records = document.root().elements()
while (records.next()) {
edits.set(records.node(), "seen", jsonBoolean(true))
edits.delete(records.node(), "note")
}
println(edits.emit())
}
// output:
// [{"id":1,"seen":true},{"id":2,"seen":true}]
jsonStringify, toJson() and emit() keep an object's members in source order. JavaScript puts array-index keys ("0", or digits without a leading zero, below 2^32 - 1) first in numeric order, then the other keys in insertion order. Pass jsKeyOrder = true to JsonNode.toJson, JsonEdits.toJson, JsonDocument.emit or JsonEdits.emit to use that ordering. Use jsonJsKeyOrder(value) for an existing Json tree. emit(true) still preserves the original number spellings, such as 1e2.
import "abla/io"
import "abla/json"
fun main {
val document = jsonDocument("{\"b\":1e2,\"10\":2,\"a\":3,\"2\":4,\"01\":5}", jsonPermissiveLimits).document
println(document.emit())
println(document.emit(true))
}
// output:
// {"b":1e2,"10":2,"a":3,"2":4,"01":5}
// {"2":4,"10":2,"b":1e2,"a":3,"01":5}
A reader (jsonObjectReader(source, jsonPermissiveLimits)) can't merge as it goes: it gives every member as written, duplicates included, in source order. Keeping the last value read for each key gives JSON.parse's result.
Forward-only reading and streaming encoding
Known-schema protocol code does not need to allocate a Json tree. An JsonObjectReader walks the source once, decodes only requested strings, and can retain a validated raw value slice:
import "abla/io"
import "abla/json"
fun main {
val source = "{\"method\":\"GET\",\"headers\":[[\"accept\",\"text/plain\"]]}"
val reader = jsonObjectReader(source)
reader.nextExpected("method")
val method = reader.readString()
reader.nextExpected("headers")
val headers = reader.readStringPairsRaw()
val valid = reader.finish()
println("$method $headers $valid")
}
// output:
// GET [["accept","text/plain"]] true
nextExpected is the order-sensitive fast path for canonical producers. nextExpectedRaw is the still leaner form when the producer guarantees ordinary unescaped UTF-8 field names; it compares the source bytes directly. JsonObjectReader.next() returns the decoded key. Inspect done to distinguish the end of the object from a valid empty key, and call finish() to check that parsing completed successfully. Consume the current value with readString, readRaw, or skip. readRaw validates any nested value without materializing it. readStringPairsRaw is a smaller fast path for the common [[name, value], ...] protocol shape. Readers retain the same input, UTF-8, depth, node, string, member, duplicate-key, and trailing-byte checks as the tree parser.
Schema readers can also traverse nested data without rescanning a retained raw slice. readObject and readArray return readers sharing the same forward parser state. Object readers additionally expose readInteger, readNumber, readBoolean and readNull; array readers use next with readString, readInteger, readNumber, readBoolean, readNull, readObject, readArray, readRaw, or skip, and both have peek. An array reader's readRaw is the object reader's for the current element: its text as the input spells it, whitespace around it skipped, nested values validated, and "" with the reader's error when the element is malformed or there is none. Call finishNested before continuing in the parent and finish on the root reader. The canonical nextExpectedRaw path fuses compact ,"name": tokens while preserving the whitespace-aware diagnostic fallback.
import "abla/io"
import "abla/json"
fun main {
val items = jsonArrayReader("[1, {\"a\": [2, 3]}, \"x\"]")
while (items.next()) println(items.readRaw())
println("${items.finish()}")
}
// output:
// 1
// {"a": [2, 3]}
// "x"
// true
Typed decoding of numeric data needs three more reads, on both readers. readNumber() reads any JSON number (fraction and exponent included) as the nearest f64, in place, without allocating; a malformed number fails with invalid_number at the number, as readInteger does. peek() gives the current value's kind without consuming it, with Json.kind's codes (0 null, 1 string, 2 number, 3 boolean, 4 array, 5 object), or -1 when there is no current value or the reader has failed. readNull() consumes a null and returns true; for anything else it returns false and leaves the value to read:
import "abla/io"
import "abla/json"
import "abla/float/text"
class Sample(val id: int, val x: f64, val y: f64, val label: string)
fun main {
val rows = jsonArrayReader(
"[{\"id\":1,\"x\":-2.5e-1,\"y\":3,\"label\":null}," +
"{\"id\":2,\"x\":0.1,\"y\":1E2,\"label\":\"edge\"}]"
)
val samples: array<Sample> = []
while (rows.next()) {
val row = rows.readObject()
row.nextExpectedRaw("id")
val id = row.readInteger()
row.nextExpectedRaw("x")
val x = row.readNumber()
row.nextExpectedRaw("y")
val y = row.readNumber()
row.nextExpectedRaw("label")
val label = if (row.readNull()) "-" else row.readString()
row.finishNested()
samples.append(Sample(id, x, y, label))
}
println("valid ${rows.finish()}")
for (sample in samples) {
println("${sample.id} ${f64Text(sample.x)} ${f64Text(sample.y)} ${sample.label}")
}
val value = jsonObjectReader("{\"v\":[1]}")
value.next()
println("kind ${value.peek()}")
}
// output:
// valid true
// 1 -0.25 3 -
// 2 0.1 100 edge
// kind 4
On an optimized build, decoding objects of 180 short numeric keys this way (tests/benchmarks/json-readers.ab) costs about 70 ns per field with nextExpectedRaw and readNumber (about 50 ns with readInteger on integer data), against about 2 µs per field for jsonParse's tree. next() costs about twice as much (150–200 ns), since it decodes every key; rejecting duplicate keys adds a hash-table lookup per key once an object has 16 members. Prefer nextExpectedRaw when the producer's key order is known.
For output, the single-pass JsonEncoder writes one validated stream without building fragments or a dynamic tree:
import "abla/io"
import "abla/json"
fun main {
val encoder = jsonEncoder()
encoder.beginObject()
encoder.encodedKey(#jsonEncodeString("ok"))
encoder.boolean(true)
encoder.key("items")
encoder.beginArray()
encoder.string("one")
encoder.integer(2)
encoder.endArray()
encoder.endObject()
println(encoder.finish())
}
// output:
// {"ok":true,"items":["one",2]}
For a static protocol key, encodedKey(#jsonEncodeString("ok")) (used for "ok" above) moves quoting and UTF-8 validation to compile time. Dynamic or untrusted keys continue to use key.
key, string, integer, boolean, nullValue, beginObject, beginArray, endObject, and endArray enforce container state while writing. The older JsonEncoded fragment constructors remain useful when composing independently produced values. Both paths avoid handwritten JSON punctuation and an intermediate dynamic object graph; LLVM can remove the DOM parser and serializer when an application uses only the forward-only APIs.
Serialization and literals
jsonStringify emits compact deterministic JSON. Object order is stored order, number text is emitted losslessly, and strings escape quotes, backslashes, and control bytes while retaining valid non-ASCII UTF-8. A manually forged invalid kind, number, string, or object shape produces the contained fallback "null"; invalid bytes are never emitted as JSON.
jsonStringifyPretty(value, sortKeys: true) returns a JsonEncoded fragment with two-space indentation, lexically sorted object keys, and no terminal newline. Use the default sortKeys: false to retain stored member order. Check valid before writing the fragment. Raw nodes, invalid values and values beyond maxDepth make it invalid. The root is depth zero.
Raw nodes: a value that is already encoded
A program that builds a large document once and sends it many times (a language service's per-file lists, say) can keep it as text instead of a tree of nodes, which costs a node for every number, string and member. A raw node (kind 6) holds one already-encoded JSON value, and jsonStringify writes its text verbatim, at the root or as an array element or object member, copied once.
import "abla/io"
import "abla/json"
fun main {
val occurrences = jsonRaw("[{\"name\":\"x\",\"range\":{\"start\":0,\"end\":1}}]")
if (occurrences != null) {
println(jsonStringify(jsonObject(["uri", "occurrences"],
[jsonString("file:///a"), occurrences])))
}
}
// output:
// {"uri":"file:///a","occurrences":[{"name":"x","range":{"start":0,"end":1}}]}
jsonRaw(text)is the checked constructor: it returnsnullunlesstextis exactly one
well-formed JSON value (valid UTF-8, no trailing input, nesting as deep as jsonParse allows, no size limit), at the cost of one validation pass. Whitespace inside the text is kept as written.
jsonRawUnchecked(text)trusts its caller and does not look attext. Iftextis not
one well-formed JSON value, jsonStringify's output is not JSON (and is not checked again). Use it only for text the program encoded itself, with jsonStringify or jsonQuote.
- A raw node reads as none of the other kinds:
isRaw()is true andisNull()...
isObject() are false, size() is 0, get(key) is JSON null and asString() is "". rawText() returns its text ("" for any other node); jsonParse that text to read the value.
jsonParse,jsonDocumentand$jsonnever produce a raw node, so a tree read from
outside never contains one.
$json constructs the same model directly. Its keys and values are Abla expressions:
import "abla/io"
import "abla/json"
class User(val name: string)
fun lookup(index: int): int = index * 10
fun tag(): string = "dynamic"
fun main {
val user = User("ada")
val count = 2
val index = 3
val literal = $json {
"answer": 42,
"ratio": 1.5e-2,
"large": 9223372036854775808,
"name": user.name,
"next": count + 1,
"item-$index": lookup(index),
"tags": ["fixed", tag()],
}
println(jsonStringify(literal))
}
// output:
// {"answer":42,"ratio":1.5e-2,"large":9223372036854775808,"name":"ada","next":3,"item-3":30,"tags":["fixed","dynamic"]}
A value that starts with { or [ is a JSON object or array; anything else is an Abla expression. A number literal on its own keeps its source text, so standard integer, fraction, and exponent forms, and integers beyond int, are never rounded. String, Boolean, and null literals map directly. Any other expression is converted by its type: Json, string, int, bool, f64, JsonNumber, and arrays of Json, string, int, f64, or bool. An f64 is written as its shortest round-trip text (f64Text), the same bytes at compile time and at run time; NaN and the infinities become null. A value of any other type is a compile error at that value.
Keys must be strings; a key of another type is a compile error at that key. A key repeated within one literal object is a compile error. Unlike JSON, an object or array may end in a comma, as "tags" and the object above do, so a literal written one member per line can add, remove, or reorder lines freely; a comma with nothing before it ([1,, 2], {,}) is a compile error. $jsons reads the same grammar.
A member can start with if (condition) in $json, $jsons, or $jsonw:
import "abla/io"
import "abla/json"
fun main {
val name = "symbol"
val declarationId = "decl"
val typeName = ""
val record = $json {
"name": name,
if (declarationId != "") "declarationId": declarationId,
if (typeName != "") "type": typeName,
}
println(jsonStringify(record))
}
// output:
// {"name":"symbol","declarationId":"decl"}
The condition must be Boolean. A false condition omits the member and skips its key and value. An object with no selected members is {}; commas are handled automatically, including when the first or last member is omitted. Guards and selected computed keys are evaluated once, in member order, before the object's values. Selected values then run in member order. An invalid selected UTF-8 key makes the entire object null and skips its values. Literal duplicate keys remain errors even when guarded. A conditional computed key, if (condition) "a" else "b": value, keeps its existing meaning.
A computed key can turn out equal to another key only when the program runs. Then the object has that key once, at the position where it first appears, with the value of the later member, in $json, $jsons and $jsonw alike (as JavaScript's JSON.parse reads a repeated key, and jsonParse with mergeDuplicateKeys), so the output never repeats a key. The later member wins, so write a fixed member after the computed ones when a key that comes from input must not replace it: $json { k: v, "role": "user" } keeps "role" as "user" whatever k is.
A value of another type is rejected with a help line listing the accepted types.
import "abla/json"
fun main {
val document = $json {"name": "a", "name": "b"}
}
// error: duplicate key "name" in a $json object
An Abla expression that starts with { or [ (a lambda or an array literal) goes in parentheses. So does a top-level value followed by an operator that should apply to the result: ($jsons count()) == expected.
$jsons uses the same grammar and immediately returns the deterministic serialized string. Its staged form is the concise choice for static protocol fixtures and headers because validation and serialization both happen during compilation:
import "abla/io"
import "abla/json"
fun main {
val body = #$jsons {
"event": "ready",
"attempt": 1
}
println(body)
}
// output:
// {"event":"ready","attempt":1}
Replace parallel key and value arrays
For a known set of fields, put each key next to its value. For example, a file-picker request can put its array of MIME types directly in the literal. Pass the resulting Json to jsonStringify if the receiving API expects text.
import "abla/io"
import "abla/json"
fun main {
val mime = ["image/png", "image/jpeg"]
val multiple = true
val types: array<Json> = []
for (item in mime) types.append(jsonString(item))
val before = jsonObject(["mime", "multiple"], [jsonArray(types), jsonBoolean(multiple)])
val request = $json {
"mime": mime,
"multiple": multiple,
}
val text = jsonStringify(request)
val equal = text == jsonStringify(before)
println("$equal")
println(text)
}
// output:
// true
// {"mime":["image/png","image/jpeg"],"multiple":true}
Keep jsonObject when the keys and values already arrive as separate arrays. When replacing existing code, check that keys stay in order and stay unique. If the bytes are part of a wire format or a fixture, compare the serialized output as well. Use $jsonw(buffer) if the caller already writes into a ByteBuffer.
The opt-in --warn-json-construction check suggests literals for JSON built with text concatenation, interpolation or buffer appends. Use the example above to review jsonObject calls with parallel arrays.
Writing directly to a buffer
$jsonw(buffer) value uses the same grammar as $json, appending one complete JSON value directly to a ByteBuffer. It returns the buffer, evaluates its buffer expression once, and preserves any bytes already there:
import "abla/bytes"
import "abla/json"
fun occurrence(name: string, begin: int, end: int): string {
val out = byteBuffer()
$jsonw(out) {"name": name, "range": {"start": begin, "end": end}}
out.toText()
}
This form constructs no runtime Json nodes, arrays of nodes, encoder state, or closures for the schema. Adjacent static keys, punctuation and literals become one append. Dynamic integers write directly into the buffer; strings share the usual quoting and UTF-8 rules; fractional/exponent literals keep their exact source spelling. Dynamic arrays of strings, integers, booleans, floats or Json values stream their elements. Nullable strings and arrays of nullable strings accept null, in both $json and $jsonw. An explicit Json input is serialized as given; it does not become another tree.
The sink must be an owned buffer place (a variable, field or indexed element) or a fresh buffer expression. Indexed places evaluate their indexes once; interpolations must keep the selected sink place stable. A saved immutable borrow cannot be used as a writer, following ordinary Abla ownership rules. Values are evaluated as they are written. Computed keys are evaluated once, before the values of their object. An invalid UTF-8 key writes null for the whole containing object and skips its values; invalid string values and nonfinite floats write null. There is no transaction around the sink: if an interpolation fails, earlier bytes remain appended. Use an ordinary Abla loop to stream complete elements with $jsonw, adding the enclosing brackets and commas outside it. Use if (condition) key: value inside an object to omit optional members without duplicating the surrounding object.
$jsonw supports staging as well: a function that writes to a fresh buffer and returns its text can run under #. tools/bench-json-stream.sh is an opt-in optimized benchmark against hand-written source-map and occurrence writers; it checks byte identity before timing prepared inputs in alternating order.
$json, #$json, $jsons, #$jsons, #jsonParse, and #jsonStringify use the same phase-safe implementation as runtime code. For the same tree, compile-time and native serialization produce identical bytes. Under #, the value expressions run at compile time too, so they may call functions but not read runtime locals.
HTTP adapter
JSON policy is separate from the base HTTP transport:
import "abla/io"
import "abla/json"
import "abla/http/json"
fun main {
val request = httpPostJson("/rpc", jsonObject(
["method"],
[jsonString("ping")]
))
val response = httpJsonValue(jsonBoolean(true), 200)
val body = request.parseJson()
println("${body.succeeded} ${body.value.get("method").asString()} ${response.status}")
}
// output:
// true ping 200
HttpRequest.parseJson accepts application/json and media types whose subtype ends in +json; matching is ASCII case-insensitive and ignores parameters. A missing or unsupported Content-Type returns unsupported_media_type without parsing the body. httpJsonLimits() currently uses the standard conservative limits.
httpJsonValue replaces every supplied Content-Type with exactly application/json; charset=utf-8. httpPostJson does the same and adds Accept: application/json only when the caller did not provide an Accept header. Other headers retain their order.
The lower-level abla/http function httpJson(string, status) remains useful when the body is already encoded and validated. Importing abla/http alone does not import or retain abla/json.
Built from compiler source ba5d6b7d. Examples and generated signatures follow that source revision.