Skip to content
Jennifer Programming Language

yaml - YAML decode / encode

Enable with use yaml;. YAML 1.2 decode / encode onto the same opaque, library-owned value that json and toml use, with the same read / walk / write surface, name for name. YAML's timestamp scalar, which JSON lacks, is surfaced through yaml.asDatetime (backed by time).

yaml.decode(text) returns an opaque yaml.Value (a KindObject, the sibling of json.Value / toml.Value); [index] and .field reject it (and == / != compare two handles by value), so use the accessors below. convert.typeOf reports "object"; convert.objectType reports "yaml.Value".

Unlike the hand-rolled json / toml / xml, yaml is backed by a Go dependency (gopkg.in/yaml.v3): full YAML (anchors and aliases, flow and block styles, implicit typing, multi-document streams) is impractical to hand-roll and has no Go standard library. The dependency is verified TinyGo-clean, so yaml builds on both binaries.

Surface

CallReturnsNotes
yaml.decode(text)yaml.ValueParse a single-document YAML string into an opaque handle. A multi-document stream errors (use decodeAll); an empty string decodes to null.
yaml.decodeWith(text, o)yaml.Valuedecode under the lower caps of a yaml.DecodeOptions{maxDepth, maxNodes} (see Decode caps).
yaml.decodeAll(text)list of yaml.ValueParse every document of a ----separated stream.
yaml.encode(v)stringRender to compact flow style ({a: 1, b: [x, y]}).
yaml.encodePretty(v)stringRender to readable block style (indented, one entry per line).
yaml.typeOf(v[, ptr])stringNode type: null / bool / int / float / string / bytes / list / map / datetime, or missing when ptr does not resolve (where has is false).
yaml.get(v[, ptr])yaml.ValueThe addressed sub-node, re-wrapped so a walk stays opaque.
yaml.has(v, ptr)boolWhether the pointer resolves.
yaml.keys(v[, ptr])list of stringKeys of the addressed mapping, in document order.
yaml.length(v[, ptr])intElement count of a list, entry count of a map.
yaml.asInt(v[, ptr])intStrict: a float node errors; an integer outside int64 is kind "yaml".
yaml.asFloat(v[, ptr])floatAn integer node promotes to float when the float holds it exactly, else kind "yaml".
yaml.asDecimal(v[, ptr])decimal.DecimalA number node as a decimal, every digit of an integer kept (json has the details).
yaml.asString(v[, ptr])string
yaml.asFloats(v[, ptr]) / asInts / asStringslist of float / int / stringA whole list in one call, each element read as asFloat / asInt / asString reads it (json has the details).
yaml.asBool(v[, ptr])bool
yaml.isNull(v[, ptr])boolWhether the addressed node is null.
yaml.asBytes(v[, ptr])bytesA !!binary node (typeOf reports bytes) as its decoded bytes.
yaml.asDatetime(v[, ptr])time.TimeA YAML timestamp scalar as a time.Time (needs use time;).
yaml.isDatetime(v[, ptr])boolWhether the addressed node is a timestamp.
yaml.map()yaml.ValueA fresh empty mapping, to build a document from scratch.
yaml.list()yaml.ValueA fresh empty sequence.
yaml.map(m) / yaml.list(xs)yaml.ValueA mapping / sequence built from a Jennifer map / list in one step (see json's "Building a large list or map").
yaml.set(v, ptr, val)yaml.ValueUpsert a map key / replace an in-range list index.
yaml.insert(v, ptr, val)yaml.ValueInsert into a list at an index or - (end).
yaml.append(v, ptr, val)yaml.ValuePush onto the list at ptr.
yaml.remove(v, ptr)yaml.ValueRemove the addressed key / element.
yaml.move(v, from, to)yaml.ValueRelocate a subtree.

The [, ptr] argument is a JSON Pointer (see below); omit it (or pass "") to address the node itself. Every write verb is non-mutating and returns a fresh handle: $v = yaml.set($v, ...), as with lists and maps.

Decoding

jennifer
use io;
use yaml;

def src as string init "title: Jennifer\n"
    + "server:\n"
    + "  host: localhost\n"
    + "  ports: [8000, 8001]\n";

def doc as yaml.Value init yaml.decode($src);
io.printf("%s\n", yaml.asString($doc, "/title"));           # Jennifer
io.printf("%d\n", yaml.asInt($doc, "/server/ports/0"));     # 8000
io.printf("%s\n", yaml.asString($doc, "/server/host"));     # localhost

Scalars are typed by YAML's implicit resolution: 42 is an int (decimal, 0x hex, and 0o octal all resolve), 3.14 a float (.inf / .nan included, though yaml.asFloat refuses those: Jennifer has no non-finite float), true / false a bool, ~ / null a null, a timestamp a datetime, and everything else a string. A quoted scalar keeps its string type ("42" stays a string), and yaml.encode re-quotes a string that reads like another type. A plain integer too large for a 64-bit int, of any length (a 0x / 0o one up to 4096 digits; longer is kind "limit"), keeps every digit: an int node that asDecimal reads and encode writes back as plain digits (a YAML 1.2 integer to any parser), not a lossy float or a string. An explicit !!float tag is a float whatever its text, and a float past float64's range (1e400, plain or tagged) is a decode error. Mappings become maps in document order; sequences become lists; a !!binary scalar decodes to a bytes node, which yaml.asBytes reads. A non-scalar mapping key (a ? [a, b] complex key) and a duplicate mapping key are both rejected.

Numbers follow YAML 1.2. The spellings YAML 1.1 parsers still read differently are a decode error naming the fix, not a guess: a leading-zero integer (012 is octal 10 to a 1.1 parser and decimal 12 to a 1.2 one; a zip code 01234 would silently become 668), 0b binary, _ digit separators (1_000), and an upper-case or signed base prefix (0X1F, -0o17). Quote such a value for a string (zip: '01234'), or write the number as plain decimal, 0x hex or 0o octal.

An explicit core tag must fit its value: !!int abc, !!binary @@@, !!null x, !!timestamp nope and a collection tagged as another kind (!!map [1]) are decode errors rather than the text kept as a string. A custom tag (!Ref name, as CloudFormation writes) carries no meaning here: its scalar decodes as the plain string, its collection as the map or list.

An alias shares the converted value of its anchor rather than copying it, so a block of defaults merged into many places is held once in memory.

Decode caps

CapDefault (jennifer / jennifer-tiny)DecodeOptions field
Nesting depth of the tree (aliases included)1000 / 64maxDepth
Tree nodes (an alias counted at every place it appears)2,097,152 / 262,144maxNodes
Nesting depth of the text, before the parse128-
Input size4 MiB / 512 KiB-

A reached cap is kind "limit". yaml.decodeWith lowers the first two per call, as json.decodeWith does: 0 keeps the default; a value above it, or a negative one, is a "runtime" error naming the allowed range.

jennifer
def doc as yaml.Value init yaml.decodeWith($text, yaml.DecodeOptions{maxDepth: 16, maxNodes: 10000});

yaml.decode guards against resource-exhaustion input with normal (catchable) decode errors: a raw-text pre-scan rejects structural nesting deeper than 128 levels before the parse runs (the underlying parser is recursive, so a deeply nested document would otherwise overflow the stack, fatally on the fixed-stack jennifer-tiny). The pre-scan follows the backing parser's own tokenizer, so quotes, plain-scalar continuation lines and block scalars cannot hide nesting from it, and input that is not valid UTF-8 (which the parser might read as UTF-16) is refused. Nesting built through aliases is held to the same per-binary limit as json (1000 levels, 64 on jennifer-tiny). An input-byte cap (4 MiB on jennifer, 512 KiB on jennifer-tiny) rejects an oversized document before the backing parser materialises its whole node tree; and a node budget (shared with the other decoders) stops an alias bomb (anchors that each reference the previous one twice) from exhausting memory. Each of these caps is kind "limit".

Errors

KindRaised for
"yaml"malformed text in decode / decodeWith / decodeAll: a syntax error, a duplicate key, an undefined alias, a scalar that does not fit its tag, a float past float64's range, a YAML 1.1-only number, a bad merge source, invalid UTF-8; more than one document in decode; a number an accessor cannot return exactly (asInt past int64, asFloat past what a float holds)
"limit"a reached cap (above)
"runtime"misuse: a wrong argument, DecodeOptions out of range, an unencodable value, an accessor on a node of another type (asBytes on a string), a malformed pointer

The decoded tree is the same compact, immutable one json and toml use, so binding, passing or yaml.get-ing a yaml.Value shares the tree instead of copying it. While decoding, the backing parser's own node tree also takes memory, briefly, for the whole document.

Anchors, aliases, and merge keys

An anchor (&name) and its aliases (*name) are resolved by value during decode: each alias reads as an independent copy (held once in memory, as above). A << merge key pulls another mapping's entries in; an explicit key always wins over a merged one, and an earlier merge source wins over a later one:

jennifer
def src as string init "defaults: &def\n"
    + "  retries: 3\n"
    + "  timeout: 30\n"
    + "service:\n"
    + "  <<: *def\n"
    + "  timeout: 60\n";
def doc as yaml.Value init yaml.decode($src);
yaml.asInt($doc, "/service/retries");   # 3  (merged in)
yaml.asInt($doc, "/service/timeout");   # 60 (own key wins)

Multi-document streams

yaml.decode handles a single document and errors on a ----separated stream, pointing at yaml.decodeAll, which returns one yaml.Value per document:

jennifer
def docs as list of yaml.Value init yaml.decodeAll($stream);
for (def d in $docs) { io.printf("%v\n", yaml.keys($d)); }

JSON Pointer (RFC 6901)

YAML has no pointer syntax of its own, so addressing reuses json's JSON Pointer; code that walks JSON walks YAML unchanged:

jennifer
yaml.get($doc, "/server/ports/0");   # first port
yaml.has($doc, "/server/tls");       # false if absent

A pointer is "" (the whole document) or a /-led sequence of tokens; ~1 escapes a literal / inside a key and ~0 a literal ~ (apply ~1 first); any other ~ is a malformed pointer. List tokens are 0 or [1-9][0-9]*.

Timestamps

yaml.typeOf reports datetime for a timestamp scalar; yaml.asDatetime returns a time.Time:

jennifer
use time;
def doc as yaml.Value init yaml.decode("created: 2001-12-15T02:59:43Z");
def t as time.Time init yaml.asDatetime($doc, "/created");
io.printf("%s\n", time.iso($t));    # 2001-12-15T02:59:43Z

A timestamp outside 1677-09-21 .. 2262-04-11 (the time.Time range, e.g. 9999-12-31) makes asDatetime throw instead of returning a wrapped instant.

Encoding

yaml.encode renders flow style (compact, {a: 1, b: [x, y]}); yaml.encodePretty renders block style (the readable, indented form), the analogue of json's compact / pretty pair. A native map / list / struct / scalar encodes directly, so a yaml.Value handle is not required; a bytes value encodes as a !!binary scalar and a time.Time as a timestamp.

jennifer
def doc as yaml.Value init yaml.decode($src);
io.printf("%s", yaml.encodePretty($doc));

A timestamp round-trips as a datetime in both styles. Flow style cannot write one with a time part (its :) as a plain scalar, so it writes it quoted with its tag: {created: !!timestamp '2001-12-15T02:59:43Z'}.

Building and editing

Start from yaml.map() / yaml.list() and grow a level at a time. Writes are strict (no auto-vivification): set creates only the final pointer segment, so build intermediate maps explicitly.

jennifer
def cfg as yaml.Value init yaml.map();
$cfg = yaml.set($cfg, "/name", "demo");
$cfg = yaml.set($cfg, "/ports", yaml.list());
$cfg = yaml.append($cfg, "/ports", 8000);
$cfg = yaml.append($cfg, "/ports", 8001);
io.printf("%s", yaml.encodePretty($cfg));
# name: demo
# ports:
#     - 8000
#     - 8001

See also

  • json / toml - the sibling config libraries yaml mirrors name for name.
  • time - the time.Time yaml.asDatetime returns.

Academy talks

TalkWhat it shows
Jennifer facing hostile inputa small YAML document refused by the node expansion cap
YAML, TOML, JSON and XMLone config in YAML 1.2, its traps and node caps