JSON, YAML, and TOML#
Meta: short page. The defining characteristic is type-driven parsing — JSON.decode produces values of the expected type. Open with that.
Each format — JSON, YAML, TOML — is a scalar type of text in that format, and, as a value, the namespace of its encode / decode static methods. They are owned by Dang, and every module gets them as builtin imports, so they work with no import statement (see Modules and imports). Data of unknown shape, whichever format it came from, is Decoded (see Keeping data undecoded). A schema's scalar of the same name (e.g. Dagger's JSON) is a separate type, reached qualified (Dagger.JSON), while unqualified JSON stays Dang's own (see Enums and scalars).
The examples on this page are live: they share one Dang environment, so later snippets use earlier definitions. Each result is computed and baked in by the docs build — edit a snippet and hit Run ▶ to replay the page in your browser. Blocks that show an error are supposed to fail: the build verifies the failure the same way it verifies the results.
Parsing#
Decoding is type-driven: the type you expect is the type you get. Here the annotation on summary tells JSON.decode to build a Summary:
type Summary {
name: String!
count: Int!
}
let summary: Summary! = JSON.decode("""{"name": "nightly", "count": 42}""")
summary.count
The type can come from a :: cast (see Types and nullability), an annotation, or a parameter or return type:
let total = JSON.decode("[1, 2, 3]") :: [Int!]!
parseSummary(text: String!): Summary! { JSON.decode(text) }
[total.length, parseSummary("""{"name": "weekly", "count": 7}""").count]
Until it has a type, a decode result has the opaque type Decoded. You can store it, pass it on, return it, encode it, or compare it with other decoded data (see Keeping data undecoded), but not use it as an Int, a String or any other particular type:
JSON.decode("1") + 1
JSON.decode("1") == 1
Give it a type first:
(JSON.decode("1") :: Int!) + 1
That includes joining it with typed values. JSON.decode(text) rescue 0 is a Decoded | Int!, which doesn't fit where an Int! is needed:
let parsed = JSON.decode("oops") rescue 0
parsed + 1
Cast inside the rescue instead:
let parsed = (JSON.decode("oops") :: Int!) rescue 0
parsed + 1
Keeping data undecoded#
Decoded is a type you can write, too. Decoding into Map[Decoded!]! (or [Decoded!]!) reads the outer object's keys and leaves each value undecoded, so data whose shape you don't know yet can be walked a level at a time. Each step is a cast:
let doc = JSON.decode("""
{"modules": [{"name": "a", "pin": {"rev": 3}}], "version": 2}
""") :: Map[Decoded!]!
let mods = doc["modules"]! :: [Map[Decoded!]!]!
[doc.keys, mods[0]!.keys]
(mods[0]!["pin"]! :: Map[Int!]!)["rev"]
A field typed Decoded! keeps whatever it was given, and encoding writes it back as the data it is:
type Entry {
name: String!
extra: Decoded!
}
let entry = JSON.decode("""{"name": "e", "extra": {"deep": [true]}}""") :: Entry!
JSON.encode(entry)
Decoded data compares with other decoded data as data: key order, number spelling and even the format it came from don't matter. Comparing it with a typed value still needs a cast first:
(JSON.decode("""{"a": 1.50, "b": [true]}""") :: Decoded!) ==
(YAML.decode("b: [true]\na: 1.5") :: Decoded!)
A later cast reads the data the way its decode would have: under the decoding format's field names, and strictly if the decode was strict (see Strict decoding).
To branch on what decoded data holds, case on it with type patterns. An arm matches when the data has its type's shape: the right kind of value (number, string, boolean, list, map or object), and for an object every key the type requires, all the way down. Matching runs none of your code; only the matching arm's data is then converted, exactly like a cast, so a constructor that raises or a scalar's new() that rejects the data is an error of the case, not a reason to try the next arm. The first matching arm wins. Lists and maps are patterns too, matched by the shape of their elements. Since any data may match none of the arms, else is required:
kind(d: Decoded!): String! {
case (d) {
n: Int! => `the number ${n}`
items: [Decoded!]! => `${items.length} items`
fields: Map[Decoded!]! => `fields ${fields.keys.join(", ")}`
else => "something else"
}
}
[kind(JSON.decode("3")), kind(JSON.decode("[1, true]")), kind(YAML.decode("b: 1\na: 2"))]
Order the arms from most to least specific: 1 is an Int and a Float (so an Int! arm after a Float! arm is an unreachable-clause error, as is a String! arm after a scalar arm, which takes every string, or an object arm after Map[Decoded!]!), and a type reads only the fields it declares (an object with extra keys still matches, unless the decode was strict). A x: Decoded! arm takes any data as it is, and so can stand in for else. An arm of a schema's scalar without a body matches any data too, since such a scalar holds data of any shape (see Enums and scalars). Null data matches no other type arm. On a nullable Decoded operand null is the operand itself being null, so it goes only to a null arm or else, and a Decoded! arm stands in for else together with a null arm; on Decoded!, null data goes to a Decoded! arm or else.
A case can't take a union that holds decoded data, such as the Decoded | Int! from JSON.decode(text) rescue 0: its arms would match the Int! by type and the data by shape. Separate the decoded data first, e.g. by rescuing to null.
Decoding works for primitives, lists, maps (Map[T], from an object), records, your own types (Objects (type)), and enums (Enums and scalars). Decoded maps have sorted keys:
JSON.decode("""{"zed": 1, "amy": 2}""") :: Map[Int!]!
Fields the type doesn't declare are ignored:
let lenient: Summary! = JSON.decode("""{"name": "x", "count": 1, "extra": true}""")
lenient.name
Strict decoding#
Pass strict: true to catch typos and stale keys instead. A key that no field of the expected type reads is an error, naming the object's path and the key. Every such key in the whole value is reported at once, one per line:
JSON.decode("""
{
"nightly": {"name": "x", "count": 1, "extra": true},
"weekly": {"name": "y", "cuont": 2, "count": 3}
}
""", strict: true) :: Map[Summary!]!
The check applies at every level of a type or record, under each field's @JSON.field(name:) key; an @JSON.ignore field reads no key, so its name is unknown too. Every field the type declares counts, including ones its constructor doesn't take (a let field), so a value's own encoding always decodes back. A Map[T]'s keys are data, so it takes any key, and so does a Decoded value until it is cast: a later cast of it is strict too (see Keeping data undecoded):
let counts = JSON.decode("""{"zed": 1, "amy": 2}""", strict: true) :: Map[Int!]!
counts["amy"]
Strict decoding also rejects a key repeated within one JSON object or YAML mapping, where a plain decode keeps the last one. TOML rejects repeated keys either way:
YAML.decode("""
nightly:
name: x
count: 1
name: y
""", strict: true) :: Map[Summary!]!
The two errors locate a problem differently. A repeated key is found while parsing, before any type is involved, so its path is the document's (nightly) and it carries a line number. An unknown key is found while building the expected type, so its path is the typed path used by every other decode error, where a map entry reads ["nightly"].
YAML anchors, aliases, and << merge keys are resolved before decoding. A mapping's own keys win over merged ones, and earlier mappings in a <<: [*a,
*b] sequence win over later ones (even with strict: true, overriding a merged key isn't a repeat):
type Server {
host: String!
port: Int!
}
let servers = YAML.decode("""
defaults: &defaults
host: localhost
port: 80
web:
<<: *defaults
port: 8080
""") :: Map[Server!]!
servers["web"]!.port
JSON.decode rejects anything after the first value:
JSON.decode("1 2") :: Int!
TOML's top level is always a table, so TOML.decode decodes into a record, an object, or a Map[T].
Empty input differs by format. JSON.decode("") raises, since it isn't valid JSON. YAML.decode("") is null (an empty YAML document), so it won't decode into a non-null record. TOML.decode("") is an empty table, so an empty TOML config still fills in declared defaults:
type Options {
retries: Int! = 3
}
(TOML.decode("") :: Options!).retries
YAML.decode("") :: Options!
Text in a format#
JSON!, YAML! and TOML! hold text in their format, checked wherever a string becomes one: a cast, a string literal where one is expected, decoding a string into one. Text that doesn't parse is an error (TOML must be a document; YAML may hold several documents, though YAML.decode reads a single one and rejects more):
let config = ("""{"name": "nightly", "count": 42}""" :: JSON!)
let deploy: YAML! = "replicas: 3"
{{config: config, deploy: deploy}}
("""{"name": """ :: JSON!)
A value is its text: it passes where a String! is expected, so decoding one works like decoding a string, and encode returns a String!, which a cast turns into the scalar:
let nightly = JSON.decode(config) :: Summary!
let nightlyText: String! = JSON.encode(nightly)
{{count: nightly.count, text: (nightlyText :: JSON!)}}
A cast also converts between such scalars and others, validating at the target, as a schema's JSON scalar needs: j :: Dagger.JSON!, and (d :: JSON!) back (see Enums and scalars).
Serialization#
JSON.encode(value), YAML.encode(value), and TOML.encode(value) return a String!. JSON.encode and YAML.encode keep fields in the order they are declared, as Go does for struct fields: a record's as written (see Literals), a type's as the type declares them; Decoded data has its keys sorted. TOML sorts them alphabetically:
JSON.encode({{ name: "nightly", count: 42, tags: ["ci"] }})
YAML.encode(summary)
TOML.encode needs a table (record) at the top level, and drops null fields, since TOML has no null. JSON and YAML keep them:
let draft = {{ title: "notes", author: null :: String }}
[JSON.encode(draft), TOML.encode(draft)]
TOML.encode(42)
JSON.encode writes compact JSON and escapes <, >, and & (as \u003c, \u003e, \u0026) so the output is safe to embed in HTML, like Go's json.Marshal. Pass indent to pretty-print with one copy of it per nesting level, and escapeHTML: false to keep those characters as they are:
let link = {{ label: "Tom & Jerry", tags: ["<b>"] }}
[JSON.encode(link), JSON.encode(link, escapeHTML: false)]
print(JSON.encode(link, indent: " ", escapeHTML: false))
More precisely, a record's fields follow how it was built: a literal's as written (even when it is annotated with a record type listing them differently), a selection's as selected, and a decoded record's as its type lists them. A map's entries keep their insertion order. To sort the keys of every object instead, maps included, pass sortKeys: true:
type Release {
version: String!
name: String!
notes: String @JSON.field(omitNull: true)
}
let release = Release(version: "2.2", name: "dang")
[JSON.encode(release), JSON.encode(release, sortKeys: true)]
JSON.encode(["zed": 1, "amy": 2], sortKeys: true)
YAML.encode takes sortKeys: true too. It sorts keys as YAML tools usually do, comparing runs of digits as numbers (item2 before item10):
YAML.encode(release, sortKeys: true)
toString(value) is not an encoder: it passes strings, enum values and custom scalar values through as their bare text, and writes anything else as a Dang literal (see Strings). Decoded data shows as the literal of the data it holds:
[toString("plain"), toString(JSON.decode("""{"b": [1], "a": "x"}"""))]
Field directives#
Fields serialize under their declared names by default. Per-format directives (see Directives) override that, each scoped to one codec so a rename never leaks into another format:
type Account {
displayName: String! @JSON.field(name: "display_name") @YAML.field(name: "display-name")
email: String @JSON.field(name: "email_address", omitNull: true)
secret: String! @JSON.ignore = "hidden"
balance: Int!
}
let account = Account(displayName: "Ada", balance: 10)
JSON.encode(account)
YAML only sees its own rename, so email and secret are still there:
YAML.encode(account)
@JSON.field(name: "...")— the key this field encodes to and decodes from@JSON.field(omitNull: true)— omit the field from output when its value is null (nullable fields only)@JSON.field(omitEmpty: true)— omit the field when its value is empty: null,"",0,false, or an empty list/map (like Go'somitempty, applied to the built-in string/number/bool/list/map kinds; useomitNullinstead if you want to keep""/0/false)@JSON.ignore— exclude the field from encoding and decoding entirely@YAML.*and@TOML.*are the same directives for their formats; a field can carry one set per format it customizes (@JSON.fieldand@YAML.fieldon the same field rename it differently per codec). The same directive cannot be applied twice for one format.
Both encode and decode honor them, so a renamed field round-trips:
An @JSON.ignore field is never read on decode, so give it a default (or make it nullable) if it would otherwise be required. The same goes for omitEmpty on a required field: an empty value is dropped on encode, so without a default the field cannot be decoded back. The name must be a string literal, and two fields cannot map to the same key.
Coercion during parsing#
Enum values decode from their names, custom scalars from their string forms, and data of any shape into Decoded (see Keeping data undecoded). A missing field takes its declared default (so does an explicit null for a non-null field with a default, except a Decoded! field, which holds null data as it is), and a missing nullable field decodes to null:
enum Outcome { PASSED FAILED }
type Build {
outcome: Outcome!
branch: String! = "main"
notes: String
}
let build = JSON.decode("""{"outcome": "PASSED"}""") :: Build!
[build.branch, build.notes]
build.outcome == Outcome.PASSED
Common errors#
Bad input raises an error naming the format, or the path to the field that went wrong:
JSON.decode("{") :: Summary!
JSON.decode("""{"name": "x"}""") :: Summary!
JSON.decode("""{"name": "x", "count": "many"}""") :: Summary!
JSON.decode("""{"outcome": "BROKEN"}""") :: Build!
All of these are recoverable with rescue (Errors: raise and rescue):
(JSON.decode("{") :: Summary!) rescue { e: Error! => e.message }
A type with no constructor, such as a namespace (Random, an import's) or a schema's object type, can't be decoded into. That is a type error, caught before anything runs, wherever a decoded value must become one — a non-null target, its non-null elements, or a required field:
JSON.decode("{}") :: Random!
A nullable position, such as a nullable field, type-checks: it decodes as null when the data leaves it out, and fails if the data has a value there. Write Decoded! for data of any shape (see Keeping data undecoded).
Meta: A side-by-side "JSON in / Dang value out" table would be a nice teaching tool.