nish/json-typed
Decode a JSON object into a class, and encode a class back, with code the compiler writes from the class's fields.
import {
JSON_DECODE_DUPLICATE,
JSON_DECODE_MAP_LIMIT,
JSON_DECODE_MISSING,
JSON_DECODE_OK,
JSON_DECODE_RANGE,
JSON_DECODE_TAG,
JSON_DECODE_TYPE,
JSON_DECODE_UNKNOWN,
JsonDecoder,
JsonNumber,
jsonDecode,
jsonDecodeUnion,
jsonEncode,
jsonEncodeBooleanArray,
jsonEncodeBooleanArrayOrNull,
jsonEncodeF64Array,
jsonEncodeF64ArrayOrNull,
jsonEncodeI32Array,
jsonEncodeI32ArrayOrNull,
jsonEncodeI64Array,
jsonEncodeI64ArrayOrNull,
jsonEncodeNumber,
jsonEncodeStringArray,
jsonEncodeStringArrayOrNull,
jsonEncodeU32Array,
jsonEncodeU32ArrayOrNull,
jsonEncodeU64,
jsonEncodeU64Array,
jsonEncodeU64ArrayOrNull,
} from "nish/json-typed";
import { JsonLimits } from "nish/json-tokenizer";
import { JsonWriter } from "nish/json";
import { JsonDecoder, jsonDecode, jsonEncode } from "nish/json-typed";
class Point { x: i32 = 0; y: i32 = 0 }
const d = new JsonDecoder(body, 0, toI32(body.length), new JsonLimits());
const p = new Point();
if (jsonDecode(d, p) === 0) {
const w = new JsonWriter(out, 0);
jsonEncode(w, p); // out[0 .. w.end) is {"x":..,"y":..}
}
jsonDecode
Decodes the JSON object d holds, the whole input, into out.
jsonDecodeUnion
Decodes the JSON text d reads into a tagged union, T: the object's tag picks the variant.
jsonEncode
Writes value to w as one JSON object, its fields in declaration order, the text JSON.stringify writes for it, in the writer's modes.
jsonEncodeBooleanArray
Writes an array whose every element is a boolean.
jsonEncodeBooleanArrayOrNull
Writes null, or the array as jsonEncodeBooleanArray writes it.
jsonEncodeF64Array
Writes an array whose every element is an f64, a NaN or an infinity as the writer writes one.
jsonEncodeF64ArrayOrNull
Writes null, or the array as jsonEncodeF64Array writes it.
jsonEncodeI32Array
Writes an array whose every element is an i32.
jsonEncodeI32ArrayOrNull
Writes null, or the array as jsonEncodeI32Array writes it.
jsonEncodeI64Array
Writes an array whose every element is an i64.
jsonEncodeI64ArrayOrNull
Writes null, or the array as jsonEncodeI64Array writes it.
jsonEncodeNumber
Writes a JsonNumber as the text it holds, byte for byte.
jsonEncodeStringArray
Writes an array whose every element is a string.
jsonEncodeStringArrayOrNull
Writes null, or the array as jsonEncodeStringArray writes it.
jsonEncodeU32Array
Writes an array whose every element is a u32.
jsonEncodeU32ArrayOrNull
Writes null, or the array as jsonEncodeU32Array writes it.
jsonEncodeU64
Writes a u64 as its digits: at most 20 of them, written with raw from an array of this call's own that nothing keeps.
jsonEncodeU64Array
Writes an array whose every element is a u64, each as jsonEncodeU64 writes it.
jsonEncodeU64ArrayOrNull
Writes null, or the array as jsonEncodeU64Array writes it.
JsonDecoder
One decoding: a tokenizer over the input and the sticky error.
JsonNumber
A JSON number kept as the text it was written in, so that no digit is lost: an integer wider than a u64 and a fraction with more digits than an f64 holds are decoded and encoded again byte for byte.
What is generated, and from what
jsonDecode(d, out) and jsonEncode(w, value) are generic, and the bodies written below are not what runs natively:
the compiler lowers every call in place, in the module that makes it, to code
it writes from the layout of the class the call binds T to
(src/json-typed.ts, src/emit-json.ts).
That code is straight-line calls into the methods of JsonDecoder and the
functions here for each field, and into JsonWriter's, so all of the parsing
is the tokenizer's and all of the writing is the writer's. A field may be an
i32, u32, i64, u64, f64 (or number), boolean or string, a
numeric enum (its number), a string enum (its member's string), a class
decoded the same way, a tagged union of
classes, a JsonNumber, an array of any of those, a Map<string, V> (a
JSON object) whose V is any of these, or a string, class, union, array or
map | null; anything else is refused at the call, naming the field
(docs/LANGUAGE.md, "Typed JSON").
Call shapes
jsonDecode(d, out) reads the one JSON object d holds
into out, a declared class, and answers d.failed: JSON_DECODE_OK (0)
or the first error's code. jsonEncode(w, value) writes value to the
writer w as one JSON object and answers nothing; the writer's own sticky
code reports a failure. The decoder is a JsonDecoder, a JsonTokenizer
over the input and a sticky error, and the encoder is the JsonWriter the
call is given, so the encoding is written in the writer's modes: a writer
set with setIndent(2) encodes what JSON.stringify(v, null, 2) writes,
and a setStrict(true) writer fails a NaN or infinite f64 field with
JSON_WRITE_NON_FINITE.
What a field may be
What a field may be, and how each maps:
Field type JSON Decoded with Encoded with
i32, u32, i64 an integer, no fraction or d.i32(), w.i32, w.u32,
exponent, in the type's d.u32(), w.i64
range d.i64()
u64 digits alone, no sign, d.u64() jsonEncodeU64
fraction or exponent, up to
2^64 - 1
numeric enum E the number of one of E's d.i32(), then w.i32
members a switch
string enum E the string of one of E's d.enumString(), w.string of
members then its bytes the member's
against each string
member's
f64 (number in f64 mode) any number; past the double d.f64() w.f64
range an infinity, which the
writer writes as null
boolean true, false d.boolean() w.boolean
string, string | null a string, and null for the d.string(cur) w.string,
second jsonEncodeStringOrNull
class C, C | null an object, and null for the C's own C's own
second decoding, into encoding
the object the
field holds
T[], T[] | null an array, and null for the d.i32Array(cur) jsonEncodeI32Array
second and its kin, or and its kin, or
C's or E's per C's or E's per
element element
Map<string, V>, or | null an object whose keys are the keys in order, entries in the
map's, each value a V each value set map's order
JsonNumber any number, kept as the text d.number(n) jsonEncodeNumber
it is written in
tagged union U, U | null an object whose tag names a the variant's the variant's
variant, and null for the decoding, into encoding, its
second the object held tag first
when its tag
matches
A Map's V is any type in this list, | null or not, a Map included;
JsonNumber may stand alone, be | null, be an array's element or be a
Map's value. The code written for a nested class, an array's element class,
a | null field's class and a Map's values is the same code, so it
recurses as the data does.
Anything else is refused at the call's argument, naming the class and the
field (NL2485 for a field type, such as an f32, an i32[][], a
Level[][], a Set, an array of maps, a Map not keyed by string (an
enum key included) or a Map whose values cannot be written, and a generic
class of the program's own). An enum that mixes string and numeric members
is not one the language declares (NL1043), an enum is never | null
(NL2010) and a const enum is refused where it is declared (NL2285).
A value that is not a declared class (an interface, a generic class or any other type) is NL2486; decoding into an interface is left for a later version. A call inside a generic function is checked for each class an instantiation binds.
Reading the class
A class the decoder has to make itself, an array's
element past the end, a | null field that holds null or a map's value,
is made with new C(), so its constructor takes no parameters (NL2488).
Decoding assigns every field, so a readonly one is refused (NL2487). A
decode stores what it makes into the object it fills, so a call inside a
using a = arena() block is refused (NL2424); an encoding only reads the
object and keeps nothing, so it may run inside one. Two fields holding one
object are decoded into it twice, the second winning.
Finding the field
The code written for a class of three or more fields
switches on the key's length in bytes, so a key is compared only with the
names of that length. Where three or more names share a length, it switches
once more, on the key's byte at the one position where those names differ
most, and calls keyIs for each name with that byte there, in declaration
order; a byte none of them has is an unknown key at once. One or two names
are compared in turn with keyIs.
A key with an escape has no byte to switch on there and is compared with
every name of its length, so "id" is the field id; a field name that is
not ASCII is dispatched by its UTF-8 bytes like any other.
The decoding rules
A JSON object's keys are the class's field names, byte for byte, or the keys its options give them, found by the key's length and then, among three or more names of that length, by one of its bytes:
class Account {
static readonly json = { rename: { userId: "user_id" }, optional: ["tags"] };
...
}
The compiler reads that literal; it is not a field. Every field is required
but an optional one, whose missing key sets it to its initializer, a key may
appear once, and a key that names no field is an error unless ignoreUnknown
is set, when its value is stepped over, checked but not kept. A number must
fit its field: an integer field takes an integer written without a fraction
or an exponent and in the field's range, and f64 takes any number.
null is accepted only by a field whose type is | null. Fields are written
to out as they are read, in the input's order: a nested object is decoded
into the object the field already holds, an array's elements into the
elements it already has, with new ones made past its end and the rest dropped
(so a reused object reuses its arrays and objects, and Arena.used() stays
flat: it is flat over 1,000 decodes of a three-level object), and a string
field keeps the string it holds when the input's is equal.
A string that changes is a new string, made by one String.fromBytes,
straight from the input when it has no escape and from its unescaped bytes
when it has one. A class the decoder has to make — an array element past the
array's end, a | null field that holds null, or a map's value — is made
with new C().
A map is emptied once the object opens, then each key is read as a new string
and its value as a V made fresh for the key (a zero, "", the enum's first
member, null, or a new object, array or map) and set, so the entries are
the input's, in the input's order. A key the object gave already is
JSON_DECODE_DUPLICATE before its value is read, however either is escaped.
A value whose read fails is not set, so a map never holds a value the input
did not give.
Unlike the rest of a decode, a map's entries are made anew each time, so
decoding into a map allocates its keys and values. Every map of one decoding
takes at most maxMapKeys keys between them (4,096 unless set), the keys of
a map inside another map included; the key past it is JSON_DECODE_MAP_LIMIT
before it is read, and reset starts the count again. At 0 or below no map
may take a key, and {} is the one map value accepted. Encoding writes the
entries in the map's own order, which is insertion order.
That differs from a JavaScript object in one case: a key that reads as an
array index ("1") keeps its place, where JSON.parse would move it first.
A class's options
A class's options are one static readonly json object literal written
in the class, which the compiler reads when it writes the class's code. It
is not a field: it has no slot, the class's layout is what it would be
without it, and the program cannot read it. It is the one static member a
class may declare. A class without it is decoded exactly as before. Its
options are checked where the class is declared, whether or not any call
decodes the class. There are three, each a literal and none a default
other than being absent:
-
rename, an object mapping a field to its key on the wire, a string literal of any bytes.{"user_id":7}is decoded intouserIdanduserIdis encoded as"user_id"; the field's own name is then a key no field has. The key is dispatched like any other, escapes and non-ASCII included. Without it a field's key is its name. -
optional, an array of field names whose key may be missing. A missing one sets the field to its initializer, on a fresh object and on one decoded into again, so a reused object keeps nothing an earlier input gave it, and allocates nothing to do it. An optional field needs an initializer. A key that is given is read like any other: once, and of its field's type. Without it every field is required and a missing key isJSON_DECODE_MISSING. presence, described below. Without it nothing is recorded.-
tag, a string literal: what a variant of a tagged union writes as its tag, described below. Without it, or withtag: "", the tag is the enum member's name, or for a string enum the member's string.
Each misuse has its own diagnostic:
NL2492 `static json` without `readonly` but with a type, `static
readonly json` with a type annotation, or on a generic class
NL2493 options, `rename`, a key or an `optional` entry not written as
the literal it must be (a module constant, an array for the
object, a string for `optional`'s array); `presence` or one of
its entries not an object literal of string literals
NL2494 an option other than `rename`, `optional`, `presence` and `tag`
NL2495 a name that is not one of the class's fields; `presence` naming
a field or a presence field the class does not declare
NL2496 a rename to a value that is not a string
NL2497 two fields with one key (a rename to another field's own name
included), or a field renamed or made optional twice
NL2498 an optional field with no initializer
NL2499 a rename to a key that is not valid UTF-8, a lone surrogate such
as `"\ud800"` included, which no input could give
NL2592 a presence field that is not a `boolean`, is `readonly`, is the
field it records, records two fields, is recorded by a presence
field of its own or is renamed or made optional; a field
recorded twice
NL2722 a `tag` that is not a string literal
NL2724 a `tag` on a class with no field whose type is one enum member
A spread in the literal is refused (NL2711), a computed key as it is
anywhere (NL1041), a subclass by extends, and a second static readonly json is a duplicate member. The options are not a value: User.json names a
class where a value is due, and is refused as any class name there is.
Only static readonly json may leave out its type: written static json = { ... }, or as an instance field, it is an ordinary field to the parser and
needs one, and an instance field called json with a type is an ordinary
field, read and written under its own name. A field or a method called json
may come before or after the options. Under Node the literal is a static
property of the class that nothing reads.
Which keys were given
An optional field's missing key and a key given
the field's initializer leave the same value; the presence option tells
them apart. It names, for a field, a boolean field of the same class that
each decoding sets to whether the input gave that field's key — true for a
key given null too:
class UserPatch {
static readonly json = { optional: ["name", "email"], presence: { name: "hasName", email: "hasEmail" } };
name: string = "";
email: string | null = null;
hasName: boolean = false;
hasEmail: boolean = false;
}
Any field can be recorded, of any kind and optional or not. A presence field is off the wire: no key reads it, encoding leaves it out, and no option renames it, makes it optional or records it. It is set when the object closes, from the flag the decoder already keeps per field to find a duplicate or a missing key, so recording costs one store per recorded field and allocates nothing, and a class that records nothing compiles to the code it did before.
Each object sets its own, so a nested class or an array element answers for
its own keys. A decoding that fails may set some of them and not others (when
the input is not an object, none), so read them only when jsonDecode
answered JSON_DECODE_OK.
A merge patch (RFC 7396)
A merge patch (RFC 7396) is that option's use: a patch class whose
every field is optional and recorded, decoded and then applied a field at a
time — a recorded key replaces its member, null on a | null field
removes it, an object field is applied the same way one level down, and an
array is replaced whole. null on a field that is not | null is
JSON_DECODE_TYPE, so a patch that removes what the type cannot lose is
refused before any of it is applied. examples/merge-patch.ts is the
recipe in full.
A tagged union
A union of classes, each with a field whose type is
one member of one enum (readonly kind: Kind.Num = Kind.Num), is written
as one object whose tag picks the variant:
enum Kind { Num, Neg }
class Num { readonly kind: Kind.Num = Kind.Num; value: f64 = 0 }
class Neg {
static readonly json = { tag: "negate" };
readonly kind: Kind.Neg = Kind.Neg;
arg: Expr;
constructor() { this.arg = zero() }
}
type Expr = Num | Neg; // {"kind":"negate","arg":{"kind":"Num","value":2}}
let e: Expr = zero();
e = jsonDecodeUnion(d, e); // d.failed says whether it worked
jsonEncode(w, e);
The tag's key is the tag field's name, or its rename, and every variant
gives the same one (NL2721). Its value is the enum member's name (a string
enum's member's string), or the variant's tag option, and no two variants
write the same one (NL2720). The
tag may be any key of the object: when it is the first, the variant is picked
at once; when it is not, the keys before it are stepped over, checked but not
kept, and the object is read again from its first key once the variant is
known. A nested union does the same inside the bytes its parent read ahead
over only when it is decoded, so each byte of the input is read again at
most once per level of nesting above it: at most maxDepth times
(docs/security/json.md, JSON-17), counted in JsonDecoder.unionReread.
jsonDecode decodes into the object it is given and cannot change which
class that is, so a union is decoded with jsonDecodeUnion(d, prev), which
answers the object it decoded into: prev when the tag names prev's
variant, a new one made by new V() when it does not or prev is null,
and prev when the decode fails (NL2719 refuses jsonDecode of a union;
NL2723 refuses jsonDecodeUnion of anything else). A union field, a union
array's element and a | null union field follow the same rule. Encoding
writes the tag first, then the variant's fields. A variant decoded alone,
by jsonDecode, reads its tag like any field and fails with
JSON_DECODE_TAG when it is not its own. The code is written once per
union, so a recursive union is one function that calls itself, and a
Map<string, Expr> decodes and encodes each value through it.
A failed decode answers prev at the top only. A union field, element or
map value below it whose tag named another variant already holds the new
variant when the failure comes, decoded up to it, as any failed jsonDecode
leaves what it read: check d.failed before using the object.
Errors are sticky codes
Errors are sticky codes, as the tokenizer's and the writer's are. The
first error sets failed to a negative code — a JSON_DECODE_* code here,
or the tokenizer's own JSON_TOK_ERR_* code when the text is not JSON or
crosses one of its JsonLimits — and errorAt to the byte offset of the
token it was found at. Every later call does nothing, and jsonDecode
answers failed; reset starts over. Nothing an input holds panics. After
an error, out holds a value of its type in every field, some of them
decoded and some as they were: an enum field or element never holds a number
that is no member's, because such a number is not stored. The codes:
Code Value Condition errorAt
JSON_DECODE_OK 0 nothing has failed
JSON_DECODE_TYPE -20 a value of the wrong JSON type the value
JSON_DECODE_RANGE -21 a number its field cannot hold the number
JSON_DECODE_UNKNOWN -22 a key that names no field the key
JSON_DECODE_DUPLICATE -23 a key given twice the second
JSON_DECODE_MISSING -24 a field the object lacks the object's `}`
JSON_DECODE_MAP_LIMIT -25 more than maxMapKeys map keys the first key past it
JSON_DECODE_TAG -26 a union's tag missing, not a the tag's value, or
string, or no variant's the object's `{`
JSON_TOK_ERR_* -1 to -13 text that is not JSON, or past the tokenizer's
a JsonLimits limit
Limits. The recursion is the data's, so the tokenizer's depth limit
bounds it: the caller's JsonLimits.maxDepth, 128 by default. Each level is
one native frame, so a limit raised into the hundreds of thousands can run
off the stack, and one kept to a few thousand cannot. The writer refuses a
65th open container (JSON_WRITER_MAX_DEPTH), so a value decoded from
deeper than 64 levels encodes as JSON_WRITE_TOO_DEEP, as does an object
that holds itself; the encoding stops at the first failure. A full buffer
is the writer's JSON_WRITE_FULL. A duplicate of a key ignoreUnknown
steps over is not detected, because its value is never read. A map is
bounded by maxMapKeys, and a number's length by JsonLimits.maxNumberBytes.
A numeric enum is its number
It is read with d.i32(), so a
number that is not an i32 integer is that field's JSON_DECODE_RANGE, and
an integer that is not the value of one of its members is
JSON_DECODE_TYPE; a member's name, "High", is a string and a type error
too. Two members of one value are one number. It is written as w.i32 of
its value, as JSON.stringify writes a TypeScript numeric enum.
A string enum is its member's string
It is read with d.enumString()
and the string's bytes are matched against the members' strings by length,
then by a byte, then with keyIs, so the read allocates nothing; an escaped
string matches as its unescaped bytes. A string that is no member's string,
and a value that is not a string, are JSON_DECODE_TYPE, and the field keeps
the member it held. It is written as w.string of the member's string, as
JSON.stringify writes a TypeScript string enum.
A `u64` is exact to 2^64 - 1
It is read through the tokenizer's
numberU64, so 18446744073709551615 decodes and 18446744073709551616,
-1, -0 and 1.5 are JSON_DECODE_RANGE. It is written as its digits,
which JSON.stringify cannot do for a number past 2^53.
A `JsonNumber` is a number's text
A field of it decodes and encodes any
number byte for byte: an integer wider than a u64, a fraction with more
digits than an f64 holds, 1E+400 and -0 alike. It is read as a number
whole, not as an object, so anything but a number is JSON_DECODE_TYPE, and
its length is bounded by JsonLimits.maxNumberBytes like any number's.
Decoding into one reuses its bytes, so Arena.used() stays flat over
decodes into one object.
Encoding
Encoding writes the fields in declaration order, each through the
writer method of its type, so the text is what JSON.stringify writes for
the same object; the writer's own sticky code reports a full buffer. A
presence field is left out. The keys come back in the order they were
written when the object is decoded from text whose keys are in that order.
Under Node
Under Node the types are erased, so there is no layout to generate the
code from: jsonDecode and jsonEncode end the program with a panic
naming this, rather than guessing a type from whatever value a field holds
(docs/LANGUAGE.md, "Typed JSON", class C). Everything else here runs there,
so a program may run the decoder's readers and the writer under Node and
get the lines the native program gets; the translation of a class is a
function per class of the same calls into JsonDecoder and JsonWriter. A
program that imports std/json-typed.ts by path rather than as
nish/json-typed is compiled as written and gets those bodies natively too.
Every name here is json-prefixed, as std/json.ts explains, and every
code is an i32, so the module is the same under --number-mode f64.
Functions
jsonDecode
Decodes the JSON object d holds, the whole input, into out. The
compiler writes the code from T's fields at every call, in the module that
makes it; under Node this body ends the program with a panic, because the
types are erased. Called as jsonDecode(d, out), with T the class of out;
every field of every class it reaches must be a type the module header lists,
and a class the decoder makes must have a constructor with no parameters.
The top-level value must be an object, or the answer is JSON_DECODE_TYPE,
and nothing but blanks may follow it. A call inside a using a = arena()
block is refused (NL2424).
const jsonDecode: <T>(d: JsonDecoder, out: T) => i32
dJsonDecoderrequired
The decoder over the input; its failed and errorAt say what
went wrong, and reset starts it over.
outTrequiredThe object to decode into: a declared class, whose fields, nested objects and arrays are reused.
returnsi32
d.failed: JSON_DECODE_OK, or the first error's code, a
JSON_DECODE_* or the tokenizer's JSON_TOK_ERR_*.
jsonDecodeUnion
Decodes the JSON text d reads into a tagged union, T: the object's tag
picks the variant. When it is prev's, prev is decoded into and
returned, its fields, nested objects and arrays reused; otherwise a new
object of that variant is made with its constructor of no parameters and
returned. The tag may be any key of the object; it is cheapest first. The
compiler writes the code from the union's variants at every call, and T
is never written at the call; under Node this body ends the program with a
panic, because the types are erased.
const jsonDecodeUnion: <T>(d: JsonDecoder, prev: T) => T
dJsonDecoderrequired
The decoder over the input; its failed and errorAt say what
went wrong, and reset starts it over.
prevTrequiredThe value the union holds now, reused when the tag names its variant.
returnsT
The decoded value; on any failure prev, perhaps partly
overwritten, with d.failed set to the first error's code, such as
JSON_DECODE_TAG.
jsonEncode
Writes value to w as one JSON object, its fields in declaration order,
the text JSON.stringify writes for it, in the writer's modes. The compiler
writes the code from T's fields at every call; under Node this body ends
the program with a panic, because the types are erased. A full buffer is
the writer's JSON_WRITE_FULL, and a value deeper than 64 levels, or one
that holds itself, its JSON_WRITE_TOO_DEEP.
const jsonEncode: <T>(w: JsonWriter, value: T) => void
wJsonWriterrequiredThe writer, whose sticky code reports any failure.
valueTrequiredThe object to write: a declared class.
jsonEncodeBooleanArray
Writes an array whose every element is a boolean.
const jsonEncodeBooleanArray: (
w: JsonWriter,
xs: boolean[],
) => void
wJsonWriterrequiredThe writer.
xsboolean[]requiredThe elements, in order.
jsonEncodeBooleanArrayOrNull
Writes null, or the array as jsonEncodeBooleanArray writes it.
const jsonEncodeBooleanArrayOrNull: (
w: JsonWriter,
xs: boolean[] | null,
) => void
wJsonWriterrequiredThe writer.
xsboolean[] | nullrequiredThe elements, or null.
jsonEncodeF64Array
Writes an array whose every element is an f64, a NaN or an infinity as the writer writes one.
const jsonEncodeF64Array: (w: JsonWriter, xs: f64[]) => void
wJsonWriterrequiredThe writer.
xsf64[]requiredThe elements, in order.
jsonEncodeF64ArrayOrNull
Writes null, or the array as jsonEncodeF64Array writes it.
const jsonEncodeF64ArrayOrNull: (
w: JsonWriter,
xs: f64[] | null,
) => void
wJsonWriterrequiredThe writer.
xsf64[] | nullrequiredThe elements, or null.
jsonEncodeI32Array
Writes an array whose every element is an i32.
const jsonEncodeI32Array: (w: JsonWriter, xs: i32[]) => void
wJsonWriterrequiredThe writer.
xsi32[]requiredThe elements, in order.
jsonEncodeI32ArrayOrNull
Writes null, or the array as jsonEncodeI32Array writes it.
const jsonEncodeI32ArrayOrNull: (
w: JsonWriter,
xs: i32[] | null,
) => void
wJsonWriterrequiredThe writer.
xsi32[] | nullrequiredThe elements, or null.
jsonEncodeI64Array
Writes an array whose every element is an i64.
const jsonEncodeI64Array: (w: JsonWriter, xs: i64[]) => void
wJsonWriterrequiredThe writer.
xsi64[]requiredThe elements, in order.
jsonEncodeI64ArrayOrNull
Writes null, or the array as jsonEncodeI64Array writes it.
const jsonEncodeI64ArrayOrNull: (
w: JsonWriter,
xs: i64[] | null,
) => void
wJsonWriterrequiredThe writer.
xsi64[] | nullrequiredThe elements, or null.
jsonEncodeNumber
Writes a JsonNumber as the text it holds, byte for byte.
const jsonEncodeNumber: (
w: JsonWriter,
n: JsonNumber,
) => void
wJsonWriterrequiredThe writer.
nJsonNumberrequiredThe number.
jsonEncodeStringArray
Writes an array whose every element is a string.
const jsonEncodeStringArray: (
w: JsonWriter,
xs: string[],
) => void
wJsonWriterrequiredThe writer.
xsstring[]requiredThe elements, in order.
jsonEncodeStringArrayOrNull
Writes null, or the array as jsonEncodeStringArray writes it.
const jsonEncodeStringArrayOrNull: (
w: JsonWriter,
xs: string[] | null,
) => void
wJsonWriterrequiredThe writer.
xsstring[] | nullrequiredThe elements, or null.
jsonEncodeU32Array
Writes an array whose every element is a u32.
const jsonEncodeU32Array: (w: JsonWriter, xs: u32[]) => void
wJsonWriterrequiredThe writer.
xsu32[]requiredThe elements, in order.
jsonEncodeU32ArrayOrNull
Writes null, or the array as jsonEncodeU32Array writes it.
const jsonEncodeU32ArrayOrNull: (
w: JsonWriter,
xs: u32[] | null,
) => void
wJsonWriterrequiredThe writer.
xsu32[] | nullrequiredThe elements, or null.
jsonEncodeU64
Writes a u64 as its digits: at most 20 of them, written with raw from an
array of this call's own that nothing keeps. A value past 2^63 has no
i64 to go through the writer's i64 as, so every u64 takes this one
loop. Every u64 here is built with toU64, a BigInt under Node.
const jsonEncodeU64: (w: JsonWriter, v: u64) => void
wJsonWriterrequiredThe writer.
vu64requiredThe value.
jsonEncodeU64Array
Writes an array whose every element is a u64, each as jsonEncodeU64 writes it.
const jsonEncodeU64Array: (w: JsonWriter, xs: u64[]) => void
wJsonWriterrequiredThe writer.
xsu64[]requiredThe elements, in order.
jsonEncodeU64ArrayOrNull
Writes null, or the array as jsonEncodeU64Array writes it.
const jsonEncodeU64ArrayOrNull: (
w: JsonWriter,
xs: u64[] | null,
) => void
wJsonWriterrequiredThe writer.
xsu64[] | nullrequiredThe elements, or null.
Classes
JsonDecoder
One decoding: a tokenizer over the input and the sticky error. Make one per
connection and reset it per request; nothing it does allocates but the
strings it decodes, the arrays it grows and the objects it makes.
class JsonDecoder
| Member | |
|---|---|
new JsonDecoder(src: u8[], off: i32, len: i32, limits: JsonLimits) |
A decoder over src[off, off + len), with no error and no map key taken. |
errorAt: i32 |
The byte offset in the input of the token the error was found at; -1 until one. |
failed: i32 |
JSON_DECODE_OK, or the first JSON_DECODE_* or JSON_TOK_ERR_* code. |
ignoreUnknown: boolean |
Step over a key that names no field instead of failing with JSON_DECODE_UNKNOWN. |
mapKeys: i32 |
The keys the maps of this decoding have taken so far; reset clears it. |
maxMapKeys: i32 |
The most keys every Map field of one decoding may take together, 4,096 unless set; past it, JSON_DECODE_MAP_LIMIT. At 0 or below, no map may take a key, so a map's only accepted value is {}. |
unionReread: i32 |
The bytes this decoding has read twice: for each tagged union whose tag was not its first key, those from its { to the end of its tag, which the decoder read ahead over and then reads again as the variant's fields. A byte is read again once for each union object it is inside, so this is at most maxDepth times the input's length (docs/security/json.md, JSON-17), and it stops at i32's largest value, 2147483647, which only raised limits reach; reset clears it. It counts the spans enterUnion reads again, not the keys unionTag steps over to find a tag. |
beginArray(): boolean |
Takes the next value as the opening of an array. |
beginObject(): boolean |
Takes the next value as the opening of an object. |
boolean(): boolean |
The next value as a boolean. |
booleanArray(xs: boolean[]): boolean[] |
The next value as an array whose every element is a boolean, into xs.Each element overwrites the slot xs already has or is pushed past its end, and the slots left over are popped, so an array no longer than xs allocates nothing. A value that is not an array fails with JSON_DECODE_TYPE, or with the tokenizer's code when the input is malformed, and leaves xs untouched; a failure inside the array leaves its contents unspecified. |
booleanArrayOrNull(xs: boolean[] | null): boolean[] | null |
The next value as null, or as an array booleanArray reads, into xs when it is an array and into a new one when it is null. |
f64(): f64 |
The next value as an f64: any number, the nearest double, and past the double range an infinity. |
f64Array(xs: f64[]): f64[] |
The next value as an array whose every element is an f64, read as f64() reads one, into xs.Each element overwrites the slot xs already has or is pushed past its end, and the slots left over are popped, so an array no longer than xs allocates nothing. A value that is not an array fails with JSON_DECODE_TYPE, or with the tokenizer's code when the input is malformed, and leaves xs untouched; a failure inside the array leaves its contents unspecified. |
f64ArrayOrNull(xs: f64[] | null): f64[] | null |
The next value as null, or as an array f64Array reads, into xs when it is an array and into a new one when it is null. |
i32(): i32 |
The next value as an i32: an integer written without a fraction or an exponent, from -2^31 to 2^31 - 1. A numeric enum is read with it too. |
i32Array(xs: i32[]): i32[] |
The next value as an array whose every element is an i32, read as i32() reads one, into xs.Each element overwrites the slot xs already has or is pushed past its end, and the slots left over are popped, so an array no longer than xs allocates nothing. A value that is not an array fails with JSON_DECODE_TYPE, or with the tokenizer's code when the input is malformed, and leaves xs untouched; a failure inside the array leaves its contents unspecified. |
i32ArrayOrNull(xs: i32[] | null): i32[] | null |
The next value as null, or as an array i32Array reads, into xs when it is an array and into a new one when it is null. |
i64(): i64 |
The next value as an i64: an integer written without a fraction or an exponent. Any integer isInteger accepts fits an i64, so there is no range to check. |
i64Array(xs: i64[]): i64[] |
The next value as an array whose every element is an i64, read as i64() reads one, into xs.Each element overwrites the slot xs already has or is pushed past its end, and the slots left over are popped, so an array no longer than xs allocates nothing. A value that is not an array fails with JSON_DECODE_TYPE, or with the tokenizer's code when the input is malformed, and leaves xs untouched; a failure inside the array leaves its contents unspecified. |
i64ArrayOrNull(xs: i64[] | null): i64[] | null |
The next value as null, or as an array i64Array reads, into xs when it is an array and into a new one when it is null. |
key(): string |
The current key, decoded: a Map field's key. |
keyByte(at: i32): i32 |
Byte at of the current key when the key has no escape, so that its bytes are the input's, and -1 otherwise: for a key with an escape, for an at outside it, and when the current token is not a key or string. A -1 matches no byte of a field's name, and the code written for a class then compares the key with each name of its length through keyIs, which decodes the escapes. |
keyLength(): i32 |
The current key's length in bytes once decoded, or -1 when the current token is not a key or string: what the code written for a class switches on before it compares a key's bytes with a field's name. |
mapRoom(): boolean |
Whether the maps of this decoding may take another key, the current one: whether they have taken fewer than maxMapKeys between them, counting it as taken when they may. A key is counted here, before its value is read, so the keys of a map inside another map count before the outer key's value is whole, and the total never passes the limit. JSON_DECODE_MAP_LIMIT at the key when they may not. |
nextElement(): boolean |
Whether the open array has another element, whose first token is then held for the read that follows. |
nextField(): boolean |
Reads the next key of the open object, or its end. |
number(n: JsonNumber): void |
The next value as a JsonNumber: its text, copied into n's bytes exactly as the input writes it. Anything but a number is JSON_DECODE_TYPE, and n keeps the number it held. Its bytes are reused, and grown only for a longer number. |
reset(src: u8[], off: i32, len: i32): void |
Starts over on src[off, off + len), keeping the limits, ignoreUnknown and maxMapKeys, and clearing any error and the count of map keys taken. |
string(cur: string): string |
The next value as a string: cur itself when the input's string is equal to it, which allocates nothing, and a new string otherwise. |
stringArray(xs: string[]): string[] |
The next value as an array whose every element is a string, read as string(cur) reads one, each against the string its slot holds, into xs.Each element overwrites the slot xs already has or is pushed past its end, and the slots left over are popped, so an array no longer than xs grows nothing. Only the container is reused: an element whose text changed is a new string. A value that is not an array fails with JSON_DECODE_TYPE, or with the tokenizer's code when the input is malformed, and leaves xs untouched; a failure inside the array leaves its contents unspecified. |
stringArrayOrNull(xs: string[] | null): string[] | null |
The next value as null, or as an array stringArray reads, into xs when it is an array and into a new one when it is null. |
text(): string |
The current key or string as a new string, made by one String.fromBytes: straight from the input when it has no escape, and from its unescaped bytes when it has one. |
u32(): u32 |
The next value as a u32: an integer written without a fraction or an exponent, from 0 to 2^32 - 1. The bounds are compared and never computed with, so under Node a number beside a BigInt is fine. |
u32Array(xs: u32[]): u32[] |
The next value as an array whose every element is a u32, read as u32() reads one, into xs.Each element overwrites the slot xs already has or is pushed past its end, and the slots left over are popped, so an array no longer than xs allocates nothing. A value that is not an array fails with JSON_DECODE_TYPE, or with the tokenizer's code when the input is malformed, and leaves xs untouched; a failure inside the array leaves its contents unspecified. |
u32ArrayOrNull(xs: u32[] | null): u32[] | null |
The next value as null, or as an array u32Array reads, into xs when it is an array and into a new one when it is null. |
u64(): u64 |
The next value as a u64: an integer written in digits alone, with no sign, fraction or exponent, up to 2^64 - 1, read through the tokenizer's numberU64. A negative number, -0 included, and one past 2^64 - 1 are JSON_DECODE_RANGE, as a fraction is. |
u64Array(xs: u64[]): u64[] |
The next value as an array whose every element is a u64, read as u64() reads one, into xs.Each element overwrites the slot xs already has or is pushed past its end, and the slots left over are popped, so an array no longer than xs allocates nothing. A value that is not an array fails with JSON_DECODE_TYPE, or with the tokenizer's code when the input is malformed, and leaves xs untouched; a failure inside the array leaves its contents unspecified. |
u64ArrayOrNull(xs: u64[] | null): u64[] | null |
The next value as null, or as an array u64Array reads, into xs when it is an array and into a new one when it is null. |
JsonNumber
A JSON number kept as the text it was written in, so that no digit is lost:
an integer wider than a u64 and a fraction with more digits than an f64
holds are decoded and encoded again byte for byte. A field of this class is
read and written as one number, not as an object: jsonDecode copies the
number's text into it, and jsonEncode writes that text back unchanged.
It reads its text as nish/json-value reads a number (numberText,
isI64, i64, isU64, u64, f64), through a tokenizer of its own, so
the two answer alike; the two are separate types until the typed layer
can name a JsonValue's number directly.
A new one holds 0. Decoding into one reuses its bytes, so an object
decoded again with numbers no longer than before allocates nothing for
them. Its length is bounded by JsonLimits.maxNumberBytes like any
number's, and anything but a number read into it is JSON_DECODE_TYPE.
setText(t) sets it when t is one JSON number and answers whether it was.
Its methods run under Node.
class JsonNumber
| Member | |
|---|---|
new JsonNumber() |
A number that holds 0. |
bytes: u8[] |
The text is bytes[0, count), one JSON number; the bytes past it are room. |
count: i32 |
How many of bytes are the number's text, 1 for the 0 a new one holds. |
f64(): f64 |
The number as an f64. |
i64(): i64 |
The number as an i64. |
isI64(): boolean |
Whether the number is an i64. |
isU64(): boolean |
Whether the number is a u64. |
setText(text: string): boolean |
Sets the text to text when it is one JSON number and nothing else; any other text leaves the number as it was. |
text(): string |
The number's text. |
u64(): u64 |
The number as a u64. |
Constants
-23
JSON_DECODE_DUPLICATE: i32
A key the object already gave, a field's or a Map's, however either is
escaped; errorAt is the second. A key ignoreUnknown steps over is not
checked, because its value is never read.
-25
JSON_DECODE_MAP_LIMIT: i32
More keys, over every Map field one decoding fills, than maxMapKeys;
errorAt is the first key past the limit. The global Map hashes a
string under a per-process random key, so a body cannot choose keys that
collide, and this limit bounds what all the maps of one decoding hold
together (docs/security/json.md, JSON-13).
-24
JSON_DECODE_MISSING: i32
An object that ended without a required field of the class; errorAt is its closing brace.
0
JSON_DECODE_OK: i32
Nothing has failed.
-21
JSON_DECODE_RANGE: i32
A number its field cannot hold: a fraction or an exponent for an integer
field, a value outside its range, or a negative number, -0 included, for
a u64. errorAt is the number.
-26
JSON_DECODE_TAG: i32
A tagged union's object whose tag is missing, not a string, or none of the
union's variants' wire tags, or a variant's object whose tag is not that
variant's own; errorAt is the tag's value, or the object's { when the
tag is missing.
-20
JSON_DECODE_TYPE: i32
A value of the wrong JSON type for its field: a string for an i32, an
array for a class, null for a field that is not | null, a top-level
value that is not an object, or an integer that is no member's value for
an enum. errorAt is the value.
-22
JSON_DECODE_UNKNOWN: i32
A key that names no field of the class, while ignoreUnknown is off; errorAt is the key.

