JSON and the text forms of foreign numbers come from three compiler-known
modules. Each is imported with use and has no .capt source. All of their
operations are pure.
Std::Json
use Std::Json. brings the module value Json into scope. Its operations are
sent to it.
| Written | Gives | Notes |
|---|---|---|
Json decode: t as: T |
Result[T] |
the original decoder: no size or depth limits, and a repeated member name passes unnoticed; fails with #JsonDecodeError. Decoding into a type that has an Option field needs VM 4; a List[...] or scalar target needs VM 6 |
Json decodeStrict: t as: T maxBytes: b maxDepth: d maxEntries: e maxNodes: n |
Result[T] |
strict and bounded; for any input you did not write yourself. VM 5 |
Json members: t maxBytes: b maxDepth: d maxEntries: e maxNodes: n |
Result[JsonRawObject] |
one object's members as exact source text, duplicates kept. VM 7 |
Json reencodeEcma: t indent: i maxBytes: b maxOutputBytes: o maxDepth: d maxEntries: e maxNodes: n |
Result[Text] |
parse and re-serialise as ECMAScript JSON.stringify would. VM 7 |
Json encode: v |
Json |
a value's one JSON encoding; see Writing JSON. VM 8 |
Json nullable: o |
Json |
null for None, else the value's encoding. VM 8 |
Json object: members |
Result[Json] |
an object whose keys come from data. VM 8 |
Json text: j indent: i maxBytes: b |
Result[Text] |
a document's text. VM 8 |
T is a type written as an argument: a struct, List[Text], i32,
JsonTextObject, and so on.
Decoding into a type
A JSON object decodes into a struct by field name. A field of type
Option[T] is None when the key is missing or null, and Some otherwise.
A value of the wrong kind fails. Members the struct does not name are
tolerated.
decodeStrict adds what an untrusted document needs:
- the whole input is parsed and validated, including members that will be ignored;
- a member name that appears twice in one object is refused
(
#JsonDuplicateMember), as are unpaired surrogate escapes and unescaped control characters; - an integer field must fit its type and may not be written with a fraction or exponent;
- the four limits are inclusive and you must give all of them.
maxBytesis the UTF-8 input size, at most 16 MiB.maxDepthcounts containers (the outermost is 1), at most 128.maxEntriesis members or elements per container, andmaxNodesis all values, keys excluded; both at most 1,000,000.
Its failure kinds are #JsonSyntax, #JsonTypeError, #JsonDuplicateMember,
#JsonByteLimit, #JsonDepthLimit, #JsonEntryLimit, #JsonNodeLimit and,
for a limit above its ceiling, #JsonLimitConfig. Decoding is charged one VM
instruction per input byte.
JsonTextObject is a built-in decode target for an object whose values are
all strings, such as an environment or a set of labels. It keeps every member
in source order:
| Type | Members |
|---|---|
JsonTextObject |
entries: List[JsonTextEntry] |
JsonTextEntry |
key: Text, value: Text |
It can also be the type of a field inside your own struct.
Raw members
Json members:... is for a program that must decide for itself what a
document means, such as one that has to treat duplicate keys in a particular
way or keep a number's exact spelling. It validates the whole document and
returns the top-level object's members as written:
| Type | Members |
|---|---|
JsonRawObject |
entries: List[JsonRawEntry], in source order, duplicates included |
JsonRawEntry |
key: Option[Text] (the decoded key, or None if it holds an unpaired surrogate escape), keyJson: Text (the key exactly as written, quotes included), value: Text (the value's exact source text), kind: Symbol (#Object, #Array, #String, #Number, #Bool or #Null), binary64Integer: Option[i64] |
binary64Integer is set only for a number that, rounded to an IEEE-754
double, is a finite integer in i64 range. It is a deliberately lossy view
for interoperating with JavaScript producers, not an exact decimal. The
ceilings are 64 MiB, depth 128, and 1,000,000 entries and nodes.
ECMAScript re-encoding
Json reencodeEcma:... gives exactly the text that
JSON.stringify(JSON.parse(t), null, indent) would give, for contracts that
bind those bytes. indent is 0 to 10. Duplicate keys keep the last value at
the first position; integer-like keys sort first; numbers are formatted as
ECMAScript formats doubles. No newline is added. Input and output are each
limited to 64 MiB, and #JsonOutputLimit reports output over
maxOutputBytes. It is compatibility serialisation, not canonical JSON.
Writing JSON
Writing JSON, below, builds documents with #{…} and Json
encode: and writes them with Json text:. The source module
Std::JsonEncoding still quotes strings and writes string-valued objects for
programs that must run on generation 7 and below
(The Std source modules).
Writing JSON
A program writes JSON by writing the document, never by joining text: a missing comma, a key given twice or a number spliced in as a string are mistakes a reviewer misses, and here the checker catches them. Writing JSON is new in VM generation 8, which is in development (Versions and VM generations); a program that does it needs that generation, and nothing else does.
Programs that must run on generation 7 and below still quote strings and
write string-valued objects with the source module Std::JsonEncoding
(The Std source modules).
It takes two steps. A #{…} literal, or Json encode: v, gives a Json: a
document held in the program, not text. Json text:indent:maxBytes: alone
turns one into text, with one size bound and one Result, however the
document was put together. (DR-0036
records the decision.)
The literal
module Example::Report.
use Std::Json.
struct Tool { name: Text, flags: List[Text], note: Option[Text] }.
;; The report a build step writes for the next one.
export report digest: Text timeout: i32 -> Result[Text] [
tool := Tool { name: "kikuc", flags: #( "--locked" ), note: None }.
flag := "--offline".
doc := #{
"sha256": digest,
"timeout": timeout,
"tool": (Json encode: tool),
"flags": [ "--locked", flag ],
"retries": 3,
"previous": null
}.
ret Json text: doc indent: 2 maxBytes: 64KiB.
].Inside #{ and its closing } the program is JSON, held to the strict
grammar: keys are quoted strings; strings take JSON's escapes (\n,
\u00e9, surrogate pairs as two escapes); numbers are JSON numbers, kept
exactly as written; true, false and null are themselves; there are no
trailing commas and no comments. The literal is always an object. Nested
objects and arrays are {…} and […].
A Captain value goes in only two ways: as a local's name (digest), or in
parentheses: (n + 1), (files count), (Json encode: tool), (#Running).
So every part of a literal is visibly either data or computed. A comment goes
above the literal, never inside it.
The checker refuses a malformed literal before the run, with what to write:
module Example::Unquoted.
export doc -> Result[Text] [
ret Json text: #{ count: 1 } indent: 0 maxBytes: 1KiB.
].`count` is not quoted, with the help a key is a JSON string: write
`"count": …`. A key written twice in one object, even in two spellings
such as "a" and "\u0061", is CAP-TYPE-035.
What each type becomes
Every type has one encoding, or none:
| Type | JSON |
|---|---|
Json |
itself |
Text |
a string; Text that is not valid UTF-8 stops the run (CAP-RUN-UTF8) and is never replaced |
bool |
true, false |
i32, i64 |
an integer, exactly, even beyond 2^53 |
Decimal |
its digits at its scale: 1.50, -0.5; never an exponent |
List[T] |
an array, in order |
| a struct | an object of its fields, in declared order |
Option[T] as a member or field |
the value for Some; for None the member is left out |
Symbol |
its name, without # |
Path, Url, Digest and the other tagged types |
their text |
Instant, Date |
RFC 3339 in UTC, and YYYY-MM-DD |
A None member is left out, so nothing writes a null the program did not
write. Where null is meant, say so: null in the literal, or Json
nullable: o, which is null for None. An Option anywhere but a member
or field, in an array or at the top, must be written that way.
Everything else is refused before the run, naming where the type sits and what to write instead:
module Example::Disks.
use Std::Json.
struct Disk { name: Text, size: Bytes }.
export inventory disk: Disk -> Result[Text] [
ret Json text: (Json encode: disk) indent: 0 maxBytes: 1KiB.
].`size: Bytes` has no JSON encoding: a JSON number has no unit, and
choosing one is a conversion the program should write; (Text from: q)
keeps the unit. Octets are refused too (JSON has no bytes: write (o hex),
or the encoding the reader expects), and so are enums and Result, which
have no agreed JSON form, secrets, and JsonRawObject.
Keys from data
A literal's keys are written in the program. When they come from data, use
Json object: with a list of JsonMember { key: Text, value: Json }. Keys
from data are input, so it gives a Result: a key given twice fails with
#JsonDuplicateMember.
module Example::Labels.
use Std::Json.
;; `name=value` pairs, separated by commas, as a JSON object in that order.
export labels pairs: Text -> Text [
members := List empty: JsonMember.
(pairs splitOn: ",") forEach: [ :pair |
parts := pair splitOn: "=".
members := members push: JsonMember { key: (parts at: 0), value: (Json encode: (parts at: 1)) }.
].
(Json object: members) ifOk: [ :doc |
(Json text: doc indent: 0 maxBytes: 4KiB) ifOk: [ :t | ret t ] ifFail: [ :e | ret (e message) ].
] ifFail: [ :e | ret (e message) ].
ret "".
].Text
Json text: j indent: n maxBytes: b writes members in their order, never
sorted. indent: 0 is compact; 1 to 10 is JSON.stringify's layout, a
newline and n spaces a level. Strings are escaped as JSON.stringify escapes
them. There is no final newline. The same document and indent always give the
same bytes.
It fails, as a Result, with #JsonOutputLimit when the text would be
longer than maxBytes, with #JsonDepthLimit when objects and arrays nest
deeper than 128 (the limit decodeStrict reads), and with
#JsonLimitConfig for an indent outside 0 to 10 or a maxBytes above 64
MiB. The run is charged maxBytes instructions before writing starts.
$ captain build report.capt -o report.capb
built report.capb ([..] bytes, sha256 [..])
$ captain run report.capb report digest=ab12 timeout=240000
run log: report.runlog
Ok { v: "{\n \"sha256\": \"ab12\",\n \"timeout\": 240000,\n \"tool\": {\n \"name\": \"kikuc\",\n \"flags\": [\n \"--locked\"\n ]\n },\n \"flags\": [\n \"--locked\",\n \"--offline\"\n ],\n \"retries\": 3,\n \"previous\": null\n}" }
$ captain build labels.capt -o labels.capb
built labels.capb ([..] bytes, sha256 [..])
$ captain run labels.capb labels pairs=env=prod,team=ops
run log: labels.runlog
"{\"env\":\"prod\",\"team\":\"ops\"}"
$ captain run labels.capb labels pairs=env=prod,env=test
run log: labels.runlog
"JsonDuplicateMember: the key \"env\" is given twice"tool's note is None, so it has no member.
Order
Each value in a literal is evaluated once, in the order written, and the document is built after the last. An effect in a parenthesised value runs in that order and shows in a plan in that order; a failure stops the run with no document.
Where a document goes
A Json is a value inside the program. In generation 8 it crosses no entry
and no effect: a program returns, writes or sends its text. An effect
whose signature holds a Json is refused (CAP-TYPE-037), and so is a
root module's export, when the program is built. A library module may export
procedures that take and give documents.
http post: url body: v does not take a Json: it serialises the value it
is given by its own older rules, which
Processes, HTTP and hosts describes.
Std::EcmaNumber
use Std::EcmaNumber. brings the module value EcmaNumber. Its two
operations exist to reproduce the text a JavaScript program would print for a
number, without putting floating point into the language. Both need VM 7.
| Written | Gives | Notes |
|---|---|---|
EcmaNumber divide: a by: b |
Result[Text] |
converts both texts to binary64, divides, and gives the shortest text that reads back as the same double. Negative zero is -0; non-finite results are NaN, Infinity, -Infinity |
EcmaNumber fixed: a digits: n |
Result[Text] |
ECMAScript Number.prototype.toFixed(n), n from 0 to 100 |
Each operand is at most 1024 bytes and is a JSON number or exactly NaN,
Infinity or -Infinity. Failures are #EcmaNumberSyntax,
#EcmaNumberLimit and #EcmaNumberDigits. Ordinary arithmetic stays exact;
these operations only produce text.
Std::Text
use Std::Text. brings one free procedure:
| Written | Gives |
|---|---|
split text: t on: sep |
List[Text] |
It is the same operation as the prelude's t splitOn: sep, from before that
method existed, and several library modules still use it.
Example
module Example::Release.
use Std::Json.
use Std::EcmaNumber.
struct Release { name: Text, build: i32, notes: Option[Text] }.
export summary of: Text -> Text [
(Json decodeStrict: of as: Release
maxBytes: 64KiB maxDepth: 8 maxEntries: 64 maxNodes: 256)
ifOk: [ :r |
line := (r name) append: (" #" append: (Text from: (r build))).
(r notes) ifSome: [ :n | line := line append: (": " append: n) ] ifNone: [].
ret line ]
ifFail: [ :e | ret (Text from: (e kind)) append: (": " append: (e message)) ].
].
export environment of: Text -> List[Text] [
out := List empty: Text.
(Json decodeStrict: of as: JsonTextObject
maxBytes: 4KiB maxDepth: 2 maxEntries: 32 maxNodes: 64)
ifOk: [ :o | (o entries) forEach: [ :e |
out := out push: ((e key) append: ("=" append: (e value))) ] ]
ifFail: [ :e | out := out push: (Text from: (e kind)) ].
ret out.
].
;; Seconds to one decimal place, as `(ms / 1000).toFixed(1)` prints them.
export seconds ms: Text -> Result[Text] [
(EcmaNumber divide: ms by: "1000")
ifOk: [ :q | ret EcmaNumber fixed: q digits: 1 ]
ifFail: [ :e | ret Fail { err: e } ].
].$ captain build release.capt -o release.capb
built release.capb ([..] bytes, sha256 [..])
$ captain run release.capb summary of='{"name":"tide","build":42,"notes":"fixes"}'
run log: summary.runlog
"tide #42: fixes"
$ captain run release.capb summary of='{"name":"tide","build":4.5}'
run log: summary.runlog
"JsonTypeError: Release.build: `4.5` is not an i32"
$ captain run release.capb summary of='{"name":"a","name":"b","build":1}'
run log: summary.runlog
"JsonDuplicateMember: [..]"
$ captain run release.capb environment of='{"HOME":"/root","LANG":"C"}'
run log: environment.runlog
#( "HOME=/root", "LANG=C" )
$ captain run release.capb seconds ms=1150
run log: seconds.runlog
Ok { v: "1.1" }The last result is 1.1, not 1.2: 1.15 has no exact binary64 form, and the
nearest double is a little below it. That is the behaviour the operation
exists to reproduce.