@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:
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)
}interface JsonEncode {
fn to_json() JsonValue
}JsonEncode.to_json#
Returns the JSON form of this value.
fn to_json() JsonValueJsonOptions 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.
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.
ignore_unknown_fields Bool = trueJsonOptions.max_bytes#
Maximum UTF-8 input bytes before parsing; null adds no input-size budget.
max_bytes Int? = nullJsonOptions.max_depth#
Maximum container nesting; a root scalar has depth zero, and a root container depth one.
max_depth Int? = nullJsonOptions.max_values#
Maximum parsed containers and scalar values, excluding object keys; null adds no count budget.
max_values Int? = nullJsonValue 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:
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.
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.
ArrayValue(values List[JsonValue])JsonValue.BoolValue#
A JSON true or false value.
BoolValue(value Bool)JsonValue.Null#
JSON null, represented without a payload value.
NullJsonValue.NumberValue#
An exact JSON number token; parsing does not coerce it into Float.
NumberValue(text String)JsonValue.ObjectValue#
A JSON object retaining insertion order and rejecting duplicate keys during parsing.
ObjectValue(values Map[String, JsonValue])JsonValue.StringValue#
A decoded JSON string, with escapes resolved into Unicode text.
StringValue(value String)JsonValue.ArrayValue.values#
Element values in source order; the array owns its elements.
values List[JsonValue]JsonValue.BoolValue.value#
The decoded boolean: true for JSON true, false for JSON false.
value BoolJsonValue.NumberValue.text#
Original numeric token text; stringify validates its JSON number syntax.
text StringJsonValue.ObjectValue.values#
String-keyed members in insertion order; stringify reads their current values.
values Map[String, JsonValue]JsonValue.StringValue.value#
Decoded UTF-8 text, preserving scalar contents without normalization.
value StringJsonValue.as_bool#
Returns a boolean value, or null for any other value.
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.
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.
fn as_int() Int?JsonValue.as_list#
Returns the elements of an array value as a view, or null for any other value.
fn as_list() List[JsonValue]?JsonValue.as_map#
Returns the members of an object value as a view, or null for any other value.
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.
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.
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.
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.
fn get_index(index Int) JsonValue?JsonValue.is_null#
Returns true only for the Null case; any other value returns false.
fn is_null() BoolStringifyOptions Type#
Settings for stringify: an output byte budget, pretty-print indentation, and strict
rejection of values without a JSON form.
type StringifyOptions {
max_bytes Int? = null
indent Int? = null
strict Bool = false
}StringifyOptions.indent#
Spaces per indentation level; null writes compact JSON.
indent Int? = nullStringifyOptions.max_bytes#
Maximum encoded UTF-8 bytes; null adds no output budget.
max_bytes Int? = nullStringifyOptions.strict#
True makes any value without a JSON form, anywhere in the document, return
EBADMSG.
strict Bool = falsejson_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.
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.
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
nullfor anOptionalfield. An absentVoidfield becomesvoid; any other absent required field returnsEBADMSG. A member that is not a field is ignored, unlessignore_unknown_fieldsisfalse, which makes it returnEBADMSG. - 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 asResultfollow the same rule, so{"ok":{"value":5}}reads asok(5). T?readsnullasnull.Listreads an array.- A sized integer accepts integer digits within its own range, and
Float32any finite number that fits it. Intaccepts integer digits that fit in the platform’s Int,Floatany finite number,BigIntandDecimalthe exact number text. AnullFloat, whichstringifywrites forNaNand infinities, returnsEBADMSG.Bytesreads a standard base64 string, andIpAddressandCidrtheir string forms.Timestamp,DurationandUrlare write-only: they are not standard JSON, so reading one isEBADMSG.Map[String, T]reads an object whenTisData;JsonValuekeeps 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.
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
nullis omitted; so is a field holding a value with no JSON form (Void). nullelsewhere (a list element, the root) isnull, 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 whenTisData. Other map keys andSetfail theDatabound.- The sized integers (
Int8toInt32,UInt8toUInt64) are exact decimal digits, asInt.Float32is the shortest decimal that reads back as the sameFloat32; NaN and infinities arenull. - 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. Timestampis an RFC 3339 string in UTC,Durationits integer nanoseconds,Bytesa standard base64 string,Urlits string form,IpAddressandCidrtheir text.Result, other standard records and alternatives follow the ordinary rules, sook(5)is{"ok":{"value":5}}.- A
JsonValueis written as stored, so parsed documents mix with typed data. - A type that implements
JsonEncodeis written as theJsonValueitsto_jsonreturns, 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
stringifyruns, 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.
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)fn stringify[T Data](value T, options StringifyOptions = StringifyOptions()) Result[String, Error] { ... }