Manuscript Documentation
v2026.12.0

@std/data/json.ms#

Import each required symbol with import Name from "@std/data/json.ms".

JsonEncode Interface#

Customizes how stringify encodes a type. It takes precedence over the structural encoding for every record and alternative, so use it to choose a tagged or discriminator encoding, or any other shape.

A value whose type implements it is encoded as the JsonValue its to_json returns, wherever it appears: at the root, in a field, in a list, or as a map value. The returned JsonValue is written as stored and is not customized again. Implement it in the module that defines the type.

Custom typed decoding is not supported. When the input has a different shape, parse a JsonValue and handle its cases.

The default encoding of an alternative is externally tagged, {"Created":{"id":1}}, so it round-trips through parse. This implementation writes a type discriminator member instead, a common protocol shape:

Manuscript
import JsonEncode, JsonValue from "@std/data/json.ms"

enum Event {
    Created(id Int)
    Deleted(id Int)
}

fn Event.to_json() JsonValue {
    return match self {
        Created(id) => tagged("created", id)
        Deleted(id) => tagged("deleted", id)
    }
}

fn tagged(kind String, id Int) JsonValue {
    var fields = Map[String, JsonValue]()
    fields.add("type", JsonValue.StringValue(kind.clone()))
    fields.add("id", JsonValue.NumberValue(f"{id}"))
    return JsonValue.ObjectValue(fields)
}
Manuscript
interface JsonEncode {
    fn to_json() JsonValue
}

JsonEncode.to_json#

Returns the JSON form of this value.

Manuscript
fn to_json() JsonValue

JsonOptions Type#

Settings for parse and json_reader: optional bounds on input bytes, nesting depth and parsed values, and whether object members that are not fields of T are ignored. Set the bounds when the input is untrusted.

Manuscript
type JsonOptions {
    max_bytes Int? = null
    max_depth Int? = null
    max_values Int? = null
    ignore_unknown_fields Bool = true
}

JsonOptions.ignore_unknown_fields#

True ignores object members that are not fields of T; false makes them return EBADMSG.

Manuscript
ignore_unknown_fields Bool = true

JsonOptions.max_bytes#

Maximum UTF-8 input bytes before parsing; null adds no input-size budget.

Manuscript
max_bytes Int? = null

JsonOptions.max_depth#

Maximum container nesting; a root scalar has depth zero, and a root container depth one.

Manuscript
max_depth Int? = null

JsonOptions.max_values#

Maximum parsed containers and scalar values, excluding object keys; null adds no count budget.

Manuscript
max_values Int? = null

JsonValue Enum#

A JSON value. Number text is retained to avoid losing precision during parsing.

get and get_index read one level, and the as_* methods read a scalar or container. Each returns null on a mismatch. get, get_index, as_string, as_list and as_map borrow the selected part, so keep the document alive and unchanged while you use it (or .clone() to keep a copy). For nested reads, bind each level and return early on null:

Manuscript
import JsonValue from "@std/data/json.ms"

fn user_name(doc JsonValue) String {
    user := doc.get("user")
    if user == null { return "" }
    name := user.get("name")
    if name == null { return "" }
    return name.as_string().clone() or ""
}

get_in reads a chain of object members in one call and borrows the result: doc.get_in(["user", "name"]). A JSON document is Data, including its string-keyed object members.

Manuscript
enum JsonValue {
    Null
    BoolValue(value Bool)
    NumberValue(text String)
    StringValue(value String)
    ArrayValue(values List[JsonValue])
    ObjectValue(values Map[String, JsonValue])
}

JsonValue.ArrayValue#

An ordered JSON array whose mutable list can be updated before serialization.

Manuscript
ArrayValue(values List[JsonValue])

JsonValue.BoolValue#

A JSON true or false value.

Manuscript
BoolValue(value Bool)

JsonValue.Null#

JSON null, represented without a payload value.

Manuscript
Null

JsonValue.NumberValue#

An exact JSON number token; parsing does not coerce it into Float.

Manuscript
NumberValue(text String)

JsonValue.ObjectValue#

A JSON object retaining insertion order and rejecting duplicate keys during parsing.

Manuscript
ObjectValue(values Map[String, JsonValue])

JsonValue.StringValue#

A decoded JSON string, with escapes resolved into Unicode text.

Manuscript
StringValue(value String)

JsonValue.ArrayValue.values#

Element values in source order; the array owns its elements.

Manuscript
values List[JsonValue]

JsonValue.BoolValue.value#

The decoded boolean: true for JSON true, false for JSON false.

Manuscript
value Bool

JsonValue.NumberValue.text#

Original numeric token text; stringify validates its JSON number syntax.

Manuscript
text String

JsonValue.ObjectValue.values#

String-keyed members in insertion order; stringify reads their current values.

Manuscript
values Map[String, JsonValue]

JsonValue.StringValue.value#

Decoded UTF-8 text, preserving scalar contents without normalization.

Manuscript
value String

JsonValue.as_bool#

Returns a boolean value, or null for any other value.

Manuscript
fn as_bool() Bool?

JsonValue.as_float#

Returns a number value as a Float, or null when the value is not a number or its text does not parse to a finite number.

Manuscript
fn as_float() Float?

JsonValue.as_int#

Returns a number value as an Int, or null when the value is not a number or its text has a fraction, an exponent, or digits that do not fit in Int.

Manuscript
fn as_int() Int?

JsonValue.as_list#

Returns the elements of an array value as a view, or null for any other value.

Manuscript
fn as_list() List[JsonValue]?

JsonValue.as_map#

Returns the members of an object value as a view, or null for any other value.

Manuscript
fn as_map() Map[String, JsonValue]?

JsonValue.as_string#

Returns the text of a string value as a view, or null for any other value.

Manuscript
fn as_string() String?

JsonValue.get#

Returns the object member for key, or null for an absent key or a value that is not an object. The result borrows from the receiver.

Manuscript
fn get(key String) JsonValue?

JsonValue.get_in#

Returns the value reached by reading each object member of keys in turn, or null when a member is absent, a value on the way is not an object, or keys is empty. The result borrows from the receiver.

Manuscript
fn get_in(keys List[String]) JsonValue?

JsonValue.get_index#

Returns the array element at index, counting a negative index from the end. An index out of range, or a value that is not an array, returns null. The result borrows from the receiver.

Manuscript
fn get_index(index Int) JsonValue?

JsonValue.is_null#

Returns true only for the Null case; any other value returns false.

Manuscript
fn is_null() Bool

StringifyOptions Type#

Settings for stringify: an output byte budget, pretty-print indentation, and strict rejection of values without a JSON form.

Manuscript
type StringifyOptions {
    max_bytes Int? = null
    indent Int? = null
    strict Bool = false
}

StringifyOptions.indent#

Spaces per indentation level; null writes compact JSON.

Manuscript
indent Int? = null

StringifyOptions.max_bytes#

Maximum encoded UTF-8 bytes; null adds no output budget.

Manuscript
max_bytes Int? = null

StringifyOptions.strict#

True makes any value without a JSON form, anywhere in the document, return EBADMSG.

Manuscript
strict Bool = false

json_reader Function#

Reads a sequence of JSON values of type T from a byte stream, such as JSON Lines or concatenated JSON.

Values may be separated by JSON whitespace or directly adjacent when they are strings, arrays, or objects. Top-level numbers, true, false, and null end at whitespace or at the end of the stream. Chunk boundaries may fall anywhere, including inside a token, an escape, or a UTF-8 scalar, and only the value being read is buffered. T decodes as in parse; the default JsonValue keeps each value as a document. options applies to each value separately: max_bytes counts its UTF-8 bytes, max_depth its nesting, and max_values its parsed values; an exceeded limit fails the read with EOVERFLOW. Leave the bounds unset only for trusted input, because an unterminated value is otherwise buffered without bound. Malformed or truncated input fails the read with EBADMSG, and negative limits with EINVAL. Closing the result closes input.

Manuscript
fn json_reader[T Data = JsonValue](move input ReadStream[Bytes], options JsonOptions = JsonOptions()) ReadStream[T] { ... }

json_writer Function#

Writes values of type T to a byte stream as JSON Lines: each value is encoded as stringify does, on a single line, and ends with a line feed. max_bytes bounds one encoded value and fails the write with EOVERFLOW. Writes delegate to output’s sink, which may wait. flush().wait() uses its completion condition; a pipe may retain up to capacity unread values. Closing closes output.

Manuscript
fn json_writer[T Data](move output WriteStream[Bytes], max_bytes Int? = null) WriteStream[T] { ... }

parse Function#

Parses one JSON value and applies the supplied input, depth, and value limits.

With the default T = JsonValue the result is the parsed tree. Any other T is read from the document by the inverse of the stringify encoding, and the result is a Result holding the decoded T. Name T either way: parse[Request](text) or result: Request! = parse(text). The ? operator passes no expected type, so write parse[Request](text)?.

A value whose shape does not match T returns EBADMSG; a type that is not Data is rejected at compile time. The input, depth and value limits apply to the document before decoding.

  • A record is an object. Members may appear in any order. An absent member takes the field’s default, else null for an Optional field. An absent Void field becomes void; any other absent required field returns EBADMSG. A member that is not a field is ignored, unless ignore_unknown_fields is false, which makes it return EBADMSG.
  • An alternative case without payload is its name as a string; one with payload is externally tagged, {"Circle":{"radius":2}}, with the same member rules for the labeled fields. Standard alternatives such as Result follow the same rule, so {"ok":{"value":5}} reads as ok(5).
  • T? reads null as null.
  • List reads an array.
  • A sized integer accepts integer digits within its own range, and Float32 any finite number that fits it.
  • Int accepts integer digits that fit in the platform’s Int, Float any finite number, BigInt and Decimal the exact number text. A null Float, which stringify writes for NaN and infinities, returns EBADMSG.
  • Bytes reads a standard base64 string, and IpAddress and Cidr their string forms. Timestamp, Duration and Url are write-only: they are not standard JSON, so reading one is EBADMSG.
  • Map[String, T] reads an object when T is Data; JsonValue keeps its subtree as parsed.

The record-or-document choice comes from T, not from the text: parse[Request] reads an object as a record and parse[JsonValue] keeps it as a document.

Manuscript
fn parse[T Data = JsonValue](text String, options JsonOptions = JsonOptions()) Result[T, Error] { ... }

stringify Function#

Encodes a Data value as JSON text; a type that is not Data is rejected at compile time.

  • Record fields appear in declaration order. A field holding null is omitted; so is a field holding a value with no JSON form (Void).
  • null elsewhere (a list element, the root) is null, as is a no-form list element.
  • A root value with no JSON form returns EBADMSG.
  • An alternative case without payload is its name as a string, "Dot". A case with payload is externally tagged: {"Circle":{"radius":2}}, an object keyed by the case name whose value holds the labeled fields under the record rules. Payload labels never collide with a discriminator.
  • Map[String, T] is an object when T is Data. Other map keys and Set fail the Data bound.
  • The sized integers (Int8 to Int32, UInt8 to UInt64) are exact decimal digits, as Int. Float32 is the shortest decimal that reads back as the same Float32; NaN and infinities are null.
  • Int, BigInt and Decimal are exact decimal digits. Float uses the shortest decimal that parses back to the same value; NaN and infinities are null.
  • Timestamp is an RFC 3339 string in UTC, Duration its integer nanoseconds, Bytes a standard base64 string, Url its string form, IpAddress and Cidr their text. Result, other standard records and alternatives follow the ordinary rules, so ok(5) is {"ok":{"value":5}}.
  • A JsonValue is written as stored, so parsed documents mix with typed data.
  • A type that implements JsonEncode is written as the JsonValue its to_json returns, instead of any rule above.
  • Strings are UTF-8 JSON strings; only quotes, backslashes and control characters are escaped, so <, > and & stay as written.
  • Values are read when stringify runs, so later mutation does not change the text. Ownership prevents cyclic values; each contained value is encoded where it appears.

strict makes any value without a JSON form, anywhere in the document, return EBADMSG instead of being omitted or written as null. This covers Void; functions, resources and interface values fail the Data bound at compile time. A field holding null is still omitted.

indent pretty-prints with that many spaces per level, at most 10; null or 0 is compact. Empty containers stay {} and [], and a space follows each colon. max_bytes bounds the output, indentation included; exceeding it returns EOVERFLOW. A negative bound or indent returns EINVAL.

Manuscript
import stringify from "@std/data/json.ms"

type Request {
    model String
    stream Bool
    user String?
}

text := stringify(Request(model: "example", stream: true, user: null))?
print(text)
Manuscript
fn stringify[T Data](value T, options StringifyOptions = StringifyOptions()) Result[String, Error] { ... }