json - JSON encode / decode
Enable with use json;. RFC 8259 JSON, mapped onto Jennifer's value model. Hand-rolled (no host encoding/json) so it works identically on both binaries.
Surface
| Call | Returns | Notes |
|---|---|---|
json.encode(v) | string | Compact JSON for any encodable value (including a json.Value). |
json.encodePretty(v) | string | Same, 2-space indented; empty lists / maps stay []/{}. |
json.encodeWith(v, o) | string | Same, shaped by a json.EncodeOptions (see Encode options). |
json.decode(s) | json.Value | Parse JSON text into an opaque handle (see below). |
json.decodeWith(s, o) | json.Value | Same, under the lower caps of a json.DecodeOptions{maxDepth, maxNodes} (see Decode caps). |
json.decode rejects an object that repeats a key ({"a": 1, "a": 2}) with a catchable decode error positioned at the second copy, at any depth, the same as yaml.decode and toml.decode. RFC 8259 leaves duplicates to the implementation and I-JSON (RFC 7493) forbids them; silently keeping one copy would let two parsers read the same document differently. The same key in two different objects is fine.
json.decode also rejects container nesting past a fixed depth with a normal (catchable) decode error, so hostile deeply-nested input can't exhaust the interpreter's stack. The limit is shared by every parser in the toolchain and is set per binary: 1000 levels on the default jennifer (Go's growable stack), 64 on jennifer-tiny (its fixed 4 MB stack), both far past any real document. decode also caps the total number of value nodes it will materialise (2,097,152 on jennifer, which a 4 MB list of zeros reaches; 262,144 on jennifer-tiny), so a hostile document of millions of tiny values raises a catchable error instead of growing without bound. Writes and list / map hold to the same node cap, counting a shared json.Value at every place it appears: inserting one value into itself repeatedly raises result expands to more than N nodes instead of building a value too large to encode or compare.
Errors
| Kind | Raised for |
|---|---|
"json" | malformed text in decode / decodeWith: a syntax error, a repeated key, trailing content; a number an accessor cannot return exactly (asInt past int64, asFloat past what a float holds) |
"limit" | a reached cap (below) |
"runtime" | misuse: a wrong argument, an unencodable value (NaN, a non-string map key), an accessor on a node of another type, a malformed pointer |
Decode caps
A reached cap (the nesting depth, the node count, a write's result past either) is an error of kind "limit", so a caller tells "too big" from "malformed" by kind. The toml, yaml, xml and asn1 decoders and their writes do the same.
The node cap bounds memory only loosely: a few MB of text of small values can build some 300 MB of nodes before reaching it. A service that decodes untrusted input can lower the caps per call:
use json;
def o as json.DecodeOptions;
$o.maxDepth = 32; # 0 keeps the default (1000; 64 on jennifer-tiny)
$o.maxNodes = 100000; # 0 keeps the default (about 2M; 256K on jennifer-tiny)
def doc as json.Value init json.decodeWith($text, $o);The options only lower a cap: a value above the default, or a negative one, is a "runtime" error naming the allowed range.
Accessors over a decoded json.Value. Every one takes an optional trailing JSON Pointer (RFC 6901) string, relative to the passed node ("" or omitted = the node itself):
| Call | Returns | Notes |
|---|---|---|
json.typeOf(v[, ptr]) | string | The node's type: null bool int float string list map, or missing when ptr does not resolve (where has is false). |
json.get(v[, ptr]) | json.Value | The addressed sub-node, as a json.Value (walk stays opaque). |
json.has(v, ptr) | bool | Whether the pointer resolves to an existing node. |
json.keys(v[, ptr]) | list of string | Keys of the addressed map, in document order. |
json.length(v[, ptr]) | int | Element count of a list, or entry count of a map. |
json.asInt(v[, ptr]) | int | An int node: a number written without . or exponent that fits int64. A float node, 1.0 included, errors; an integer outside int64 is kind "json". |
json.asFloat(v[, ptr]) | float | A number node; an integral one promotes (JSON has one number type) when the float holds it exactly, else kind "json" (most integers past 2^53). |
json.asDecimal(v[, ptr]) | decimal.Decimal | A number node as a decimal: an integer with every digit (outside int64 too), a float through its shortest round-trip form. |
json.asFloats(v[, ptr]) | list of float | A list node whose every element is a number, each read as asFloat reads it; else an error naming the first bad index. One call, no per-element pointer. |
json.asInts(v[, ptr]) | list of int | A list node whose every element is an int node, as asInt reads it (1.0 errors); else an error naming the first bad index. |
json.asStrings(v[, ptr]) | list of string | A list node whose every element is a string node, as asString reads it. The first other element is an error naming its index. |
json.asString(v[, ptr]) | string | A string node. |
json.asBool(v[, ptr]) | bool | A true / false node. |
json.isNull(v[, ptr]) | bool | Whether the addressed node is JSON null. |
Write surface: every verb is non-mutating, returning a fresh json.Value; the idiom is $v = json.set($v, ...):
| Call | Returns | Notes |
|---|---|---|
json.map() | json.Value | A fresh empty JSON map (object): the start of a document. |
json.map(m) | json.Value | A JSON map built from a Jennifer map of string to V in one step (insertion order). |
json.list() | json.Value | A fresh empty JSON list (array). |
json.list(xs) | json.Value | A JSON list built from a Jennifer list in one step; json.Value elements are shared, not copied. |
json.set(v, ptr, val) | json.Value | Upsert a map key, or replace an in-range list index, at ptr. |
json.insert(v, ptr, val) | json.Value | Insert val into a list before index ptr (or - = at end). |
json.append(v, ptr, val) | json.Value | Push val onto the list addressed by ptr (sugar for insert at /.../-). |
json.remove(v, ptr) | json.Value | Drop the map key or list element at ptr. |
json.move(v, from, to) | json.Value | Relocate the subtree at from to to (read, remove, then set). |
json.mergePatch(t, p) | json.Value | Apply the RFC 7386 merge patch p to t (see Merge patch). |
Encoding
json.encode walks the value and writes its JSON image:
| Jennifer | JSON |
|---|---|
null | null |
bool | true / false |
int | integer number |
float | number: plain digits for 1e-6 <= |f| < 1e21 (1000000.0), an exponent outside (1e+21, 1e-7), always with a . or exponent so it decodes back as float |
string | string (escaped) |
bytes | base64 string |
list of T | array |
map of string to V | object (in insertion order) |
| struct | object, keys in field-declaration order |
| enum | a payload-less variant as its name ("Red"), a payloaded one as {"Circle": {"r": 2.5}} |
json.Value | the document it wraps (a decode / encode round-trip) |
Encode errors (positioned at the call): a map with a non-string key, a task value, or a non-finite float (NaN / infinity have no JSON image).
HTML-safe strings. In string values the characters <, >, and &, and the line / paragraph separators U+2028 / U+2029, are escaped as \u003c, \u003e, \u0026, \u2028, and \u2029 (matching Go's default SetEscapeHTML(true)). This keeps encoded JSON safe to embed directly in an HTML <script> block or a JSONP response: a value of </script> cannot break out of the element, and the two separators cannot terminate a JavaScript string literal. The output is still valid JSON and decodes back to the exact same string, so a decode / encode round-trip is unaffected.
use io;
use json;
io.printf("%s\n", json.encode({"id": 1, "tags": ["a", "b"], "ok": true}));
# {"id":1,"tags":["a","b"],"ok":true}Encode options
json.encodeWith(v, opts) takes a json.EncodeOptions. Every field's zero value is json.encode's behaviour, so json.EncodeOptions{} changes nothing and each field opts into one difference:
| Field | Type | Effect |
|---|---|---|
indent | int | Spaces per level, 0 (compact) to 16. 2 is encodePretty. |
sortKeys | bool | Object members in key order instead of insertion / document order (lists keep theirs). Keys compare by UTF-16 code unit, as RFC 8785 and JavaScript sort them. |
rawHtml | bool | Write < > & U+2028 U+2029 as themselves, not as \u escapes, for JSON that never lands in HTML. |
canonical | bool | RFC 8785 (JCS) canonical form, for signing or hashing a document: sorted keys, no whitespace, only the escapes JSON requires, and numbers as ECMAScript writes them (1, not 1.0; -0 is 0). |
Canonical numbers are IEEE doubles, so an int beyond +/-2^53 is an error rather than a number some reader would round; send such an id as a string. canonical with a non-zero indent is an error. A decoded float comes out of canonical form as 1 and decodes back as an int: canonical text is for comparing and signing, not for a typed round trip.
use fs;
use json;
def o as json.EncodeOptions;
$o.indent = 4;
$o.sortKeys = true;
fs.writeString("config.json", json.encodeWith($cfg, $o));
def signed as string init json.encodeWith($claims, json.EncodeOptions{canonical: true});Decoding
json.decode returns an opaque json.Value, a handle onto the parsed tree. It is opaque: [index] and .field reject it (with a hint to the accessors), so a still-generic JSON node never mixes into typed code by accident. == / != are the exception: they compare two handles by value (same type and equal content), so decoded documents can be de-duplicated or matched. You reach inside with the accessors, addressing nodes by JSON Pointer, the same paths the write surface uses.
The parsed tree is compact and immutable. It is stored in a form built for JSON rather than as ordinary Jennifer values, so a document takes from about its text size (string-heavy data) to roughly 15 times it (many small values) in memory. Because nothing edits it in place, binding a json.Value, passing it to a function, capturing it in a spawn, or taking a sub-tree with json.get shares the tree instead of copying it, and each write copies only the path it changes. Strings in the tree share the decoded text, so a sub-tree from json.get keeps the whole document's text in memory; the values the as* accessors and keys return are copies, so to keep a few fields of a large document past its lifetime, read them out rather than holding a sub-tree.
use io;
use json;
def doc as json.Value init json.decode('{"x": 7, "y": 8}');
io.printf("%d\n", json.asInt($doc, "/x") + json.asInt($doc, "/y")); # 15A JSON object corresponds to a map of string to V, an array to a list of V, and a number to an int when it has no fractional or exponent part (else a float), so json.typeOf reports map / list / int / float (Jennifer's own vocabulary, not "object" / "array" / "number"). An integer outside the int64 range keeps every digit: typeOf is int, encode writes it back unchanged, asDecimal reads it, and asInt refuses it (kind "json", naming asDecimal). yaml does the same; toml refuses such a literal, as TOML 1.0 requires. convert.typeOf($doc) is the generic "object"; convert.objectType($doc) is the specific "json.Value".
A def r as json.Value; with no initializer is a JSON null node (json.isNull($r) is true).
A json.Value displays as its compact JSON, so echoing $doc at the REPL, io.printf("%v", $doc), and convert.toString($doc) all show the document (not an opaque <json.Value>); json.encodePretty($doc) is the multi-line form.
JSON Pointer (RFC 6901)
A pointer is a slash-separated list of keys and list indices, addressing exactly one node:
| Pointer | Addresses |
|---|---|
"" (or an omitted argument) | The node itself. |
/user/name | Map key user, then key name. |
/user/roles/0 | Index 0 of a list. Indices are 0 or [1-9][0-9]*: no leading zeros, no negative indices. The - end-marker is a write-only position (insert / append); reads reject it. |
/a~1b, /m~0n | Escapes: a literal / in a key is written ~1, a literal ~ is ~0 (key a/b, key m~n). Any other ~ (/a~2, a trailing ~) is a malformed pointer, an error even in has. |
Pointers are relative to the node you pass, so json.get to a subtree and short relative pointers compose:
def user as json.Value init json.get($doc, "/user");
io.printf("%s\n", json.asString($user, "/name")); # relative to $userA missing key, an out-of-range or malformed index, or descending into a scalar is a positioned error (catchable with try/catch); use json.has to test a path without raising. There is no wildcard, recursive-descent, or predicate syntax: a pointer names one node, which is what lets the write verbs target it.
To read the last element of a list, compute the index from json.length, a plain pointer with no special syntax:
use convert;
def last as int init json.length($doc, "/qux") - 1;
io.printf("%d\n", json.asInt($doc, "/qux/" + convert.toString($last)));Walking a nested document
use convert;
use io;
use json;
def doc as json.Value init json.decode(
'{"user": {"name": "ada", "roles": ["admin", "dev"]}}');
io.printf("name = %s\n", json.asString($doc, "/user/name"));
for (def i in 0..json.length($doc, "/user/roles")) {
io.printf("role = %s\n", json.asString($doc, "/user/roles/" + convert.toString($i)));
}json.typeOf branches on shape before extracting, for a field that may be absent or polymorphic: it reports missing for a pointer that does not resolve, so one call replaces a json.has check plus a type check:
match (json.typeOf($doc, "/count")) {
when "int" { $n = json.asInt($doc, "/count"); }
when "string" { $n = convert.toInt(json.asString($doc, "/count")); }
when "missing" { $n = 0; }
else { throw Error{kind: "format", message: "count must be a number"}; }
}Building and editing
The write verbs mirror the reads: same JSON Pointer addressing, but they return a new json.Value rather than mutating in place (like lists/maps), so you rebind the result:
def v as json.Value init json.map(); # {}
$v = json.set($v, "/name", "ada"); # {"name":"ada"}
$v = json.set($v, "/tags", json.list()); # {"name":"ada","tags":[]}
$v = json.append($v, "/tags", "admin"); # ...,"tags":["admin"]
$v = json.insert($v, "/tags/0", "root"); # ...,"tags":["root","admin"]
$v = json.set($v, "/tags/1", "dev"); # replace index 1
$v = json.remove($v, "/name"); # drop a key
$v = json.move($v, "/tags", "/roles"); # rename a branchThe value you store may be a scalar, a Jennifer list / map / struct (a struct normalizes to a map, bytes to a base64 string, an enum to the form json.encode gives it), or another json.Value (its tree is spliced in). Since writes never mutate, an earlier handle keeps its old value:
def a as json.Value init json.decode('{"n":1}');
def b as json.Value init json.set($a, "/n", 2);
# json.asInt($a, "/n") is 1; json.asInt($b, "/n") is 2Writes are strict: no auto-vivification. set creates only the final pointer segment; a missing intermediate is an error, as is a set/insert on a scalar or a bare null root:
def v as json.Value; # a null node
# json.set($v, "/a", 1) -> error: cannot set a member of null
# json.set(json.map(), "/a/b", 1) -> error: no key "a" (build /a first)So you build a nested document a level at a time, each parent created before its child (the same discipline XML forces). set grows a map (new key) but only replaces an in-range list slot; grow a list with append / insert. There is no deep-path creation and no negative indexing, which keeps pointers exactly RFC 6901 and unambiguous about list-vs-map intent.
The - end-of-array marker (RFC 6901's "position after the last element") is honoured by insert / append only, where it means at the end, so json.insert($v, "/xs/-", x) and json.append($v, "/xs", x) are the same push. It is a write-position, not an element: set rejects /xs/- (it never grows a list), and reads reject it too (there is no node there; the last element is length - 1).
Building a large list or map. append to the end of a list is amortised O(1), so a loop of appends is linear. Since a written value may be a Jennifer list or map holding json.Value handles, a collection gathered in plain Jennifer converts in one step with json.list(xs) / json.map(m):
def entries as list of json.Value init [];
for (def d in $decks) {
$entries[] = json.decode(fs.readString($d));
}
def index as json.Value init json.list($entries); # one conversionset of a new map key copies the map, so a map built one key at a time is O(N^2); collect into a map of string to json.Value and call json.map(m).
Merge patch
json.mergePatch(target, patch) applies an RFC 7386 JSON Merge Patch and returns the result; target is unchanged. Either argument may be a json.Value or anything json.set accepts, so a patch can be a map literal:
- a patch object merges into the target member by member, recursively;
- a member whose patch value is
nullis removed; - any other patch value (a scalar, or a whole list) replaces the target's;
- a target that is not an object becomes
{}before an object patch.
def cfg as json.Value init json.decode(fs.readString("defaults.json"));
$cfg = json.mergePatch($cfg, json.decode(fs.readString("local.json")));
$cfg = json.mergePatch($cfg, {"tls": {"cert": null}, "port": 8443});Because null means "remove", a merge patch cannot set a member to JSON null (RFC 7386, section 1), and lists are never merged element by element; use json.set / json.insert for those edits. Only the objects the patch reaches are copied.
Heterogeneous data
A JSON array or object whose values are of mixed types has no single Jennifer type: a list of T / map of string to V is homogeneous. The opaque json.Value sidesteps that: each leaf is extracted one at a time with a type-checked as*, so a document like ["Vienna", 2026, true, null, {...}, [1,2,3]] is walked freely, element by element. That is the main advantage of the handle over decoding straight into a typed collection.
No map-to-struct coercion
Jennifer does no coercion at binding boundaries (you write 5.0, not 5, for a float), and JSON decode is no exception: there is no automatic map-to-struct landing. To put JSON in a typed struct, rebuild it explicitly from the decoded handle:
def struct Point { x as int, y as int };
def d as json.Value init json.decode('{"x": 7, "y": 8}');
def p as Point init Point{ x: json.asInt($d, "/x"), y: json.asInt($d, "/y") };The encode direction has no such restriction: json.encode($p) serializes a struct to an object directly, and json.encode($d) re-serializes the decoded handle. See technical/rejected.md for why the decode coercion was declined.
See also
- convert.md -
convert.typeOf("object") andconvert.objectType("json.Value") for identifying a handle. - encoding.md - hex / base64 and character-set codecs (
jsonreuses base64 forbytes). - cheatsheet.md - every builtin at a glance.
Academy talks
| Talk | What it shows |
|---|---|
| A JSON store on disk with flatdb | reading and building the json.Value records a store holds |
| Healthcare data with Jennifer | building FHIR Patient and Observation resources from HL7 |
| Invoicing with web services: VAT, SOAP and GraphQL | reading GraphQL replies and building invoice data |
| Jennifer facing hostile input | depth and node caps with json.decodeWith |
| YAML, TOML, JSON and XML | one config decoded, typed, written back and capped |