Built on System.Text.Json with AOT-safe Utf8JsonWriter/Utf8JsonReader (no reflection). Serializes any interpreter-compatible value and parses JSON back into script objects. Supports typed reconstruction of class and struct instances via Deserialize.
An engine object serializes as what it is, one arm per kind rather than by reflection: an
AOT image trims what a reflection walk would have found, so every namespace used to serialize as the type name
"Namespace". A namespace answers its own surface, a Form its document, a script class
its fields, and a value with no shape of its own the name a script writes for it, never a CLR type name:
var Z = Bytecode.LoadNamespace(one.Bytes, "What");
print(Json.Serialize(Z));
// {"Name":"What","Namespaces":{"A":{"Name":"A","Functions":["add"]}},
// "Properties":["What","__meta"]} the label a load gave it is listed, never walked into
Serialization primitives & collections
Json.Serialize(42); // "42"
Json.Serialize(true); // "true"
Json.Serialize("hello"); // '"hello"'
Json.Serialize(null); // "null"
Json.Stringify(value, true); // pretty-print
Json.Deserialize<Dictionary<string, object>>(Json.Serialize(value)); // the raw JSON view, as one call
What Serialize returns, and why a nested result looks escaped
Json.Serialize returns a string (its typeof is string), not a JSON value. So handing its
result to something that serializes again encodes it twice: the inner call turns the object into text, and the outer
one then encodes that text as a JSON string, which by the JSON rules cannot hold a bare " and must write
\". The backslashes exist only in the outer text; parse the envelope once and the value is the JSON text you wrote,
with real quotes.
// a host that wraps a script's return value in its own JSON envelope
Json.Serialize({ "ReturnValue": Json.Serialize(Build()) }); // {"ReturnValue":"{\"X\":3,\"Y\":4}"} text inside text
Json.Serialize({ "ReturnValue": Build() }); // {"ReturnValue":{"X":3,"Y":4}} one object, one encoding
So return the value, not its serialization, wherever something else will serialize the answer: the value of a
return that a host reads (a SQLite slc_file call, an MCP tool result, an HTTP JSON body, a form document
row). The nested call is worth writing only when the consumer wants text: storing into a TEXT
column, appending to a log, or printing it. Then the escapes are the correct JSON for a string, and a reader gets the object back
by parsing a second time. Json.Stringify behaves the same way (it is a string too), and
Json.SerializeToUtf8Bytes is the same encoding as bytes.
Serialization classes & structs
Class and struct instances serialize as flat JSON by default (public fields only, no type metadata). CLR types (like ErrorInfo, CancelEventArgs) also serialize without __type by default pass {"showType": true} to include type metadata for round-trip deserialization:
Json.Serialize(person); // {"name":"John","age":30}
Options are passed via a dictionary: the literal spelling ({"pretty": true}) and an options bag read from JSON both work. Keys are names, so they follow the interpreter's case rule like every other name the spelling the option is declared with in the default C#-strict mode, any case under the REPL's .lax. A key that does not match is reported as a warning and dropped, so neither a typo nor a differently-cased key can quietly become default output. includeNonPublic and nonPublic are two different modes, not two spellings of one: the first adds the non-public members to the public view, the second replaces it so a payload meant to show the non-public side does not have to filter its own output.
Because Json.Deserialize takes no options of its own and returns a dictionary, an options bag can be written as JSON too: Json.Serialize(x, Json.Deserialize('{"showType":true}')). That is the pattern crash_json_serialize.slc uses options read as data, and a typo is visible in the literal.
// A misspelled key is reported, not swallowed, and the keys that were understood still apply
Json.Serialize(person, Json.Deserialize('{"showType":true,"typ":true}'));
// [hh:mm:ss.mmm] [WARNING] Script: Json.Serialize: ignoring unknown option 'typ'. Valid options:
// includeNonPublic, nonPublic, includeType, showType, pretty, omitDefaults.
// → {"__type":"Person","name":"John","age":30} (showType still applied)
Json.Serialize(person, Json.Deserialize('{"showTyp":true}'));
// → {"name":"John","age":30} the same warning names showTyp, which is why the tag is missing
var opts = new Dictionary<string, object>();
opts["includeType"] = true; // {"__type":"Person","name":"John","age":30} the same marker as showType
opts["includeNonPublic"] = true; // public AND private/protected fields
opts["nonPublic"] = true; // ONLY the non-public ones the complement of the line above
opts["showType"] = true; // {"__type":"Person","name":"John","age":30} script classes & structs too
opts["omitDefaults"] = true; // only the fields whose value is not their TYPE's default
// Native: Json.RoundTrip("hello") → "hello" (serialize + deserialize with __type)
// Script-level helper alias (optional):
var RoundTrip = (val) => { return Json.RoundTrip(val); };
opts["pretty"] = true; // multi-line indented output
Json.Serialize(person, opts);
omitDefaults applies to a script class or struct field whose value is its TYPE's default (0, false, "", or null), so an object that sets a few of its fields emits only those. A field whose declared initializer DIFFERS from the type default is not omitted, because the test is against the type. What is left out reads back as the default it was, exactly, since Deserialize fills an absent key with that same value. A DICTIONARY entry and an ARRAY element are never omitted: there a zero is data or a position, not a default. The comparison is exact, so a 1e-7 is not a zero, and a non-default object is emitted whole. A dictionary ENTRY is a key/value pair rather than a property, so it is never omitted; a dictionary VALUED FIELD that is null goes like any other property, while an EMPTY one does not; and an object held in an object field has its own fields treated by the same rule. That is .NET's WhenWritingDefault condition, spelled as one option.
Serialization a form and its controls
A form, or any control, serializes as its property table: an array of rows, each {"Name":..., "Type":..., "Value":...}, which is the same table ctrl.PropList() answers, followed by the members the control's OWN kind adds (Theme and the palette, Padding, GridSize, and so on, which the base table cannot carry). A control made with CreateWinControl also reports ClassName, Style and ExStyle, which is what it takes to make that window again.
The form's children follow under a Controls row of type list, and each entry is ITSELF a row, so the same triple exists at every depth: {"Name":"Button1","Type":"Button","Value":[ ...the child's rows... ]}. The entry carries the child's IDENTITY, which is why the child's own rows do not repeat it: every control in the document therefore has a name, the one the script set or <Kind><n> counted per kind among its siblings, and the name and the kind each appear once. The ROOT is the exception and has to be, because nothing above it names it: its own rows carry Name and Kind.
The root also states the LAYOUT's version, as its first row: {"Name":"Version","Type":"int","Value":1}. Kind says which host a document is and Version says which layout of it, so a document written by a NEWER engine is refused by name instead of being mis-read, while a version older than this one, and a document with no such row at all (the layout that predates it), is read normally. Only a document ROOT carries it: a child's rows and a document window's rows are part of the same document, and Json.Serialize of a bare control is a fragment of one rather than a document, so it claims no version.
A form also publishes the CLIENT area its layout was designed in, as ClientWidth and ClientHeight. They are in DESIGN units, which are the units of Left, Top, Width and Height and so of every child's geometry, and they are the one pair of rows a document states that a reader cannot set: the document says the room its layout was laid out against, so a script can CHECK that the window it rebuilt has the same room instead of assuming it, which is what a different frame changes (another monitor's DPI, another theme). A control that is not a form has the two members but not the rows, because a form is what lays children out.
An MDI frame and an MDI document window are HOSTS too, and they write the same document: the frame's root says Kind: "MdiForm" and it carries its own controls under Controls and its DOCUMENT WINDOWS under MdiChildren, each of which nests its own Controls, so a frame's whole tree travels. Neither is a Control, so before this they answered a flat object of their public members, with a handle in it and no kind at all. READING one back is what Application.FormFromJson does, and it builds WHICHEVER host the root names: a frame comes back with its document windows, each window with its own controls, and a document whose root is a single MdiChild gets an implicit frame to be parented to (a window belongs to an MDI client, and a client to a frame).
The TYPE column carries a name a SCRIPT can write, and it is as precise as the control makes possible: a scalar's name (int, bool, string, color), a registered type's (ThemeMode), a nullable's (uint?), and a list's ELEMENT type where it is known (List<string> for the item texts of a ListBox or a ComboBox, List<ControlProp> for the children of a form, whose entries are the same rows one depth down). The spelling is the engine's own, so typeof of those value answers List and List<int> is written the same way; a list whose elements were not fixed stays a bare List.
Application.FormToJson(form) writes that document and Application.FormFromJson(doc) builds a NEW form from it, its title and its controls included, and answers how many controls were created. Building is the only direction: the document becomes a fresh host (a form, an MDI frame or a document window, whichever the root names) rather than being re-applied to one a script already holds, so a form a script wants to change is changed through its own members. The pair is what makes a stored form a reusable TEMPLATE: write the document to a database, read it back, and get a live form with the same controls and the same properties. FormToJson is Json.Serialize on the same value, so a control writes one format either way. A row whose property cannot be written is a fact the document merely REPORTS (ClassName, ItemCount, ColumnCount, TabCount, ClientWidth, ClientHeight) and is skipped; any other row the control does not carry is refused by name rather than dropped. An EVENT HANDLER is not in the document and cannot be: a handler is a closure over the interpreter that made it, so serializing one answers megabytes rather than a value (one handler is about 3.8 million characters, against two thousand for a whole form) and it would mean nothing in the process that read the document back. The document carries the names instead, which is what the index is for: a template is the LOOK, and the behaviour is re-attached to it by name (copy["Button1"].Click = ...).
var src = Application.CreateForm("template");
src.Theme = ThemeMode.Custom;
src.ThemeBackground = 0x203040;
var ok = src.CreateButton("OK", 10, 10, 80, 24);
// the row a template table would hold, and a form built back out of it
var doc = Application.FormToJson(src);
var copy = Application.FormFromJson(doc);
print(Application.FormToJson(copy) == doc); // True, at every depth
Typed deserialization
Json.Deserialize("Name", json) maps the payload onto Name, and
Json.Deserialize<T>(json) is the same thing with the type as a type argument. The name is
not advisory: it has to resolve, and it has to agree with the payload's shape "List<int>"
and "IList" want a JSON array (they promise indexing), "Dictionary<string, int>"
wants a JSON object, "HashSet" builds a set from an array, "Tuple" takes a
positional array, and "Iterable" and "IEnumerable" accept either shape, because
that is what those collection predicates mean everywhere else in the language. A declared member type is
imposed inside the container as well: Dictionary<string, Person> gives Person
values and HashSet<Person> holds them, while a base-type member (int) has
nothing to impose. Every spelling the string name, the type argument, and the untyped form that infers
from __type reaches one implementation, so they agree. A declared scalar is
imposed, not merely tolerated: JSON numbers arrive as long, so
List<int> hands back ints, and the conversion is the engine's own (the one
behind Result.As<T>(), so 1.5 rounds to 2 and an overflowing
value wraps, as unchecked arithmetic does). object means leave the payload as
parsed, and a scalar payload that cannot become the named type says which payload it was rather than
reporting the name as unknown. A name that resolves to nothing, or one whose shape the payload contradicts, is an error
rather than a silent surprise.
// The name and the payload must agree
Json.Deserialize("List<int>", '[1,2]'); // a typed list
Json.Deserialize("Iterable", '{"a":1}'); // the dictionary Iterable takes either shape
Json.Deserialize("Nonsense", '{"a":1}'); // error: unknown type name
Json.Deserialize("Dictionary<string, int>", '[1,2]'); // error: array vs a dictionary name
// The generic spelling, where the target is a plain class
Json.Deserialize<Order>('{"Id":1042}'); // an Order
// A type argument that is itself generic works too, and returns what the name form returns:
Json.Deserialize<List<int>>('[1,2]'); // as "List<int>" above
// Tuples are positional Json.Serialize((1,"a")) is [1,"a"] and the LABELS come from the type
// argument, so a tuple's fields are reachable by name, not only as Item1/Item2:
var pairs = Json.Deserialize<List<(string s, int i)>>('[["a",1]]');
print(pairs[0].s + "/" + pairs[0].i); // a/1
Json.Deserialize<(string s, int i)>('["a",1]'); // a Tuple as well the bare form works too
// An element may name any supported type, containers included:
var pair = Json.Deserialize<(int i, Iterable it)>('[1,[2,3]]');
print(pair.i + "/" + pair.it.Count); // 1/2
showType round-trip reference
showType: false (current default) clean output, no __type metadata. For round-trip with CLR types, use the typed Json.Deserialize("TypeName", json) overload.
showType: true includes __type in the output, enabling universal Json.Deserialize(json) auto-dispatch to reconstruct CLR types.
Containers carry a tag too. An object has a member slot for __type, so a dictionary simply gains one: {"__type":"Dictionary","k":1}. A JSON array has no member slot, so a list, tuple or array is wrapped {"__type":"List<string>","Values":["a","b"]}, {"__type":"int[]","Values":[1,2]}. A tuple also carries its labels beside Values {"__type":"Tuple","Names":["s","i"],"Values":["x",3]} because an array has nowhere to put them. The name is the one typeof gives (string[], List<string>, Dictionary, Tuple), and a HashSet is a container too: {"__type":"HashSet<int>","Values":[1,2]}.
A value the engine serves through an INTERNAL class is written by the ROOT of the collection it stands for. The list a typed Json.Deserialize hands back carries the declaration the read was asked for in typeof (List<int>, string[], IList), and its marker is the plain List, the way any other list is written, because the marker names the SHAPE a reader rebuilds and the element type is the wrapper's own business. The same rule covers whatever wrapper comes next, and is LazyDeserializedList still answers.
A dictionary's marker is metadata, not one of its entries. {"__type":"Dictionary<string, int>","k":1} reads back as the single entry k, untyped and typed alike, and a __type key holding anything that is not a container name is ordinary data and is kept. The parser rebuilds what was tagged, so Json.Parse(Json.Serialize(x, opts)) keeps the shape it had before tagging: a list comes back a list, and a tuple comes back a Tuple with its labels. A class instance with a field literally called Values is not affected the unwrap happens only when the type name is a container name.
// A real payload: an order with a list of lines and a totals dictionary
class Line { public string Sku; public int Qty; }
class Order { public int Id; public List<Line> Lines; public Dictionary<string, int> Totals; }
// o = Order 1042, lines A-1×2 and B-7×5, totals {"qty": 7}
Json.Serialize(o); // default: clean, no metadata
// {"Id":1042,"Lines":[{"Sku":"A-1","Qty":2},{"Sku":"B-7","Qty":5}],"Totals":{"qty":7}}
var opts = new Dictionary<string, object>();
opts["showType"] = true;
Json.Serialize(o, opts); // the same payload, self-describing
// {"__type":"Order","Id":1042,
// "Lines":{"__type":"List","Values":[{"__type":"Line","Sku":"A-1","Qty":2},
// {"__type":"Line","Sku":"B-7","Qty":5}]},
// "Totals":{"__type":"Dictionary<string, int>","qty":7}}
// ↑ three shapes in one payload: the object tags itself as a member, the list needs the
// Values wrapper (an array has no member slot), and the dictionary's tag is just another
// key. A container's tag is the name typeof gives it, and a callable is tagged "Function"
// with its signature beside the marker (a JSON string has no member slot of its own).
var typed = Json.Serialize(o, opts);
Json.Deserialize(typed); // Order auto-dispatch through __type
var strict = Json.Deserialize("Order", typed);
// strict.Id == 1042, strict.Lines is a List with 2 items, strict.Totals is a Dictionary
// the wrappers are unwrapped, so the containers come back as containers and not as the
// {"__type":…,"Values":…} objects that carried them.
| Can auto-roundtrip without showType | Needs showType: true |
Primitives int, string, bool, null | CLR types in JsonTypeMap (CancelEventArgs, ScriptErrorInfo) |
Collections (arrays, List, Dictionary) | CLR types nested inside arrays / dicts |
DateTime / TimeSpan (via typed Deserialize) | ScriptFunction (fun lambdas) |
Script classes (via typed Deserialize) | |
Deserialization overloads
// 1. Universal returns Dictionary (like Parse)
var dict = Json.Deserialize('{"name":"John","age":30}');
print(dict["name"]); // "John"
// 2. Typed by class/struct reference
var p = Json.Deserialize(Person, '{"name":"Alice","age":30}');
print(p.GetInfo()); // methods and field access
// 3. Typed by class/struct name string
var p2 = Json.Deserialize("Person", '{"name":"Bob"}');
// 4. Typed by instance (infers type from prototype)
var p3 = Json.Deserialize(new Point(0,0), '{"X":10}'); // infers Point
// 5. Case-sensitive option the DEFAULT is the interpreter's case flag: C#-strict (like System.Text.Json),
// so `x` ≠ `X`; a REPL `.lax` session makes the default tolerant. An explicit argument overrides either way.
var p4 = Json.Deserialize(Point, '{"x":10}'); // case-SENSITIVE: 'x' ≠ 'X' → X=0
var p5 = Json.Deserialize(Point, '{"x":10}', false); // case-insensitive: matches 'X'
Parse (universal)
var obj = Json.Parse('{"name":"John","age":30}'); // Dictionary
var arr = Json.Parse('[10,20,30]'); // List
Validation & Format
Json.Validate('{"a":1}'); // true
Json.Format(json); // pretty-print existing JSON string
Json.Minify(json); // strip whitespace
UTF-8 bytes (no string allocation)
var bytes = Json.SerializeToUtf8Bytes(data); // byte[]
var obj = Json.Deserialize(bytes); // Dictionary from bytes
// Deserialize also accepts byte[] no separate method needed
var d = Json.Deserialize(bytes); // universal
var p = Json.Deserialize(Person, bytes); // typed from bytes
var p2 = Json.Deserialize("Person", bytes); // by name from bytes
Which form is cheaper depends on the work, and assets/language/repl/bench/bench_json_string_vs_bytes.slc measures it on your own machine: one 1.5 MB document written and read both ways, interleaved, every round printed, with the minimum reported, plus what each call ALLOCATES, which is the reading that does not drift. Allocation states the difference plainly: writing to a string allocates two extra copies of the document (the bytes it built, then the string it decoded) and reading from a string allocates one (the encode), while the byte forms build neither. WRITING is otherwise dominated by building the JSON, so the two forms land close to each other in TIME. READING is where the byte form earns its keep. The larger lever is Deserialize against Parse: the typed form also walks the result to rebuild __type objects, which on that document allocates many times the document's own size. Reach for the byte form when reading a big payload, and for Deserialize when the payload has to come back as objects. Deserialize is ONE door, reading a string and a byte[] alike, and both serializers take the same options, read by one reader.
File I/O
Json.ToFile("out.json", data);
Json.ToFile("out.json", data, true); // pretty-print
var loaded = Json.FromFile("out.json");
// Serialize class with options
var p = new Person();
print(Json.Serialize(p)); // {"name":"John","age":30}
var opts = new Dictionary<string, object>();
opts["includeType"] = true;
print(Json.Serialize(p, opts)); // {"__type":"Person","name":"John","age":30}
var opts2 = new Dictionary<string, object>();
opts2["includeNonPublic"] = true;
print(Json.Serialize(p, opts2)); // includes private fields
// Deserialize 3 ways
var d = Json.Deserialize('{"name":"Alice","age":30}'); // Dictionary
var c = Json.Deserialize(Person, '{"name":"Alice","age":30}'); // ClassInstance
var c2 = Json.Deserialize("Person", '{"name":"Bob"}'); // by type name
// Case-sensitive matching (default: true)
var p = Json.Deserialize(Point, '{"x":10}'); // 'x' ≠ 'X' X=0 (not set)
var p2 = Json.Deserialize(Point, '{"x":10}', false); // case-insensitive: X=10
// Enum serialization
enum Color { Red, Green, Blue }
print(Json.Serialize(Color)); // {"Red":0,"Green":1,"Blue":2}
var col = Json.Deserialize(Color, Json.Serialize(Color));
print(col.Red); // 0 (dictionary key access)
// Round-trip: class → flat JSON → typed class
var orig = Json.Serialize(c);
var restored = Json.Deserialize(Person, orig);
print(restored.name); // "Alice"
// Nested classes deserialize recursively
var co = Json.Deserialize(Company, '{"name":"ACME","addr":{"city":"Paris","zip":75001}}');
print(co.addr.city); // "Paris"
Merge & Select
Json.Merge(dictA, dictB); // deep-merge B into A (A is mutated)
Json.Select(dict, "path.to.field"); // dot-path access into nested dicts
Supported types: null, primitives, dictionaries, lists, class instances, struct instances, arrays. A Task is none of them and answers
null by design, since it is a handle to running work rather than data: serialize its result, or the inputs and the outcome (see
async / await). Cyclic references detected. AOT-safe via
Utf8JsonWriter/
Utf8JsonReader zero reflection. JSON keys are matched to field names case-insensitively. Missing fields keep type defaults (
"",
0,
false). If the type name specified in
Deserialize is not found, that is an error rather than a fallback a typo must not be mistaken for a deliberate cast.
Bytes support: SerializeToUtf8Bytes avoids the string allocation, and
Deserialize accepts a
string and a
byte[] alike, so no separate parse method exists for bytes.
OpenAPI from a JSON sample
Json.ToOpenApi(sample [, options]) answers an OpenAPI 3.0.3 document as text, with its schemas
inferred from one example payload, and Json.SchemaOf(sample [, options]) answers that same inferred
schema as a dictionary a script can read or edit. The sample is JSON text, UTF-8 bytes, or a value the engine
already holds (Json.Parse's answer, a dictionary literal, a class instance: anything
Json.Serialize can write). Both members walk one inference, so what SchemaOf shows is
what the document embeds.
Json.ToOpenApi('{"id":1,"name":"Ann"}'); // the document, indented
Json.ToOpenApi(sample, {"path": "/users", "title": "Users API"});
Json.ToOpenApi(sample, {"extract": true}); // nested objects become components / $ref
Json.ToOpenApi(sample, {"method": "post", "side": "request", "status": 201});
Json.SchemaOf('{"id":1}')["properties"]["id"]["format"]; // "int32"
// a captured response, written out as a spec
var doc = Json.ToOpenApi(File.ReadAllText("./sample.json"),
{"title": "Users API", "version": "1.0.0", "path": "/users"});
File.WriteAllText("./openapi.json", doc);
| Option | Default | What it states |
title | the root name | info.title |
version | 1.0.0 | info.version |
description | absent | info.description |
path | / | the path item the operation sits under; a missing leading slash is added |
method | get | get, post, put, patch, delete, head, options or trace |
rootName | Payload | names the root schema, and its component when extracting |
side | response | response, request or both |
status | 200 | the response code, 100 to 599 |
extract | false | nested objects go to components/schemas and are referenced with $ref |
formats | true | detect date-time, date and uuid |
required | none | sample marks what every merged sample carried |
additionalProperties | absent | state it explicitly, true or false; absent means the spec's default, which allows them |
pretty | true | indented output; false is one line |
What the sample decides. A boolean is boolean; a whole number is
integer with int32, or int64 once a value does not fit; a fractional
number is number with double; a string is string, plus a
format only when its shape is unambiguous; an object is object with its properties in
the order the sample wrote them; an array is array with items merged across
every element. Reading one element only would give a wrong spec on real data, so properties are unioned
and required: "sample" keeps only what every element carried. Two shapes that disagree collapse to
{} (any value), the one honest answer when the data contradicts itself, while
integer beside number widens to number. A property that is only ever
null states nothing ({}), because a null says nothing about a real value; a null mixed
with a value adds nullable: true. A reference carries nullability through
allOf, which is the only shape 3.0 allows beside a $ref.
Why the keys are lowercase. OpenAPI's member names (openapi, info,
paths, properties, $ref) are the specification's, so this is the one
document here that does not use the engine's PascalCase convention, and a schema
Json.SchemaOf answers uses the same spelling because it is the same schema. Component names are
built from the property name in PascalCase, with a numeric suffix where two would collide, and only the
specification's own alphabet is used, so a property called first name still yields a valid name.
The order of every group, and of the properties, is fixed and an absent member is omitted, which is what makes
two documents from one sample byte-identical.
A single sample cannot state an enum, a minimum or maximum, a pattern, an example, or which
fields are optional, which is why required is off by default: a spec that overstates what is
mandatory rejects payloads the API accepts. Identical nested shapes are not deduplicated, so two properties
with the same structure become two schemas. One call describes one path and one method, and a document that
merges several endpoints is the caller's to assemble. SchemaOf always answers the inline schema
whatever extract says, because a schema a script holds has no document around it to reference.
Only date-time, date and uuid are detected: email and
uri are left out because one sample cannot disprove them, and a generator reads
format as a promise. The member reads the SAMPLE, never the script's classes: a class and the
payload it serializes can disagree, and the payload is what a client sends. Version 3.0.3 is the only dialect
written; "openapi": "3.1.0" is a second emitter (3.1 replaces nullable with a type
array) and is not accepted yet.
Checking a value against a schema
Json.ValidateAgainst(schema, value) answers whether a value matches a schema, and where it does
not. It is Json.SchemaOf's pair: one member answers the schema a sample implies, the other enforces
it, so the schema a script holds is the one it can check against. The value is JSON text, UTF-8 bytes, or a value
the engine already holds, and a STRING is read as the JSON TEXT (the reading this whole namespace gives one). The
answer is a dictionary with ok, the path of the first mismatch in the notation a JSON
reader knows, and the message naming it, both empty when the value matches.
var v = Json.ValidateAgainst(Json.SchemaOf(sample), payload);
if (!v["ok"]) { print("refused: " + v["message"]); } // refused: $.id: expected an integer
// A schema a script STATES is checked too, which is where a rule a sample cannot establish belongs:
Json.ValidateAgainst({ "type": "object",
"properties": { "a": { "type": "integer" } },
"required": ["a"], "additionalProperties": false },
'{"a":1,"b":2}')["path"]; // $.b (an additional property is not allowed)
What a check covers is what a document can state: type, properties,
required, items, nullable and additionalProperties, at any
depth, with the path of the first mismatch ($, $.id, $.lines[2].qty). A
format is NOT enforced: date-time, date and uuid are shapes a
sample's text suggested, and a generator reads them as advice, so refusing a payload for a format the engine
merely guessed would reject data the API accepts. A keyword this cannot honour (enum,
$ref, oneOf, minimum) is refused by name rather than ignored, because a
constraint that is silently dropped is a contract the caller believes it has.
An integer means an integer: a fractional number is refused, even one whose value is whole, and
a null is refused unless the schema says nullable. The required list has two sources and they are
UNIONED, exactly as the document writes them: what a schema STATES, and what every merged sample carried when the
check was asked to enforce that. A route uses this same check on the request it received, which is what makes a
published contract one the server keeps.
Extending namespaces
Any namespace (including Json, File, Http, etc.) can be extended with user-defined functions or properties by simple assignment. This works because namespaces are reference types modifications are visible to all importing scripts.
// Add a function to the Json namespace
Json.Reverse = (x) => {
var chars = [c for c in x];
var result = "";
var i = Count(chars) - 1;
while (i >= 0) { result = result + chars[i]; i = i - 1; }
return result;
};
// Call it like a native method
print(Json.Reverse("hello")); // "olleh"
// Also works for properties
Json.Version = "1.0";
// Re-defining an existing method shows a warning:
Json.Serialize = (x) => "overridden!"; // ⚠ Warning: Json.Serialize already exists.
// In an include file (json_utils.inc), import once and use everywhere:
// json_utils.inc contents:
Json.Pretty = (value) => Json.Serialize(value, true);
Json.Get = (obj, path, def) => { /* nested access */ };
Json.Pick = (obj, keys) => { /* filter keys */ };
// Usage:
import "../json_utils.inc";
print(Json.Pretty([1, 2, 3]));
Avro schemas and their three encodings are a namespace of their own: see
Avro.