json

Parse JSON strings into typed silt values and serialize values to JSON. A document whose shape is not known in advance is read into a json.Value.

Summary

FunctionSignatureDescription
decode(Value, type a) -> Result(a, JsonError) where a: DecodeDecode a json.Value into a typed value
encode(a) -> Value where a: EncodeEncode a value as a json.Value
parse(String, type a) -> Result(a, JsonError) where a: DecodeParse a JSON document into a value of the type
parse_with(String, Map(String, String), type a) -> Result(a, JsonError) where a: DecodeAs json.parse, each field the map names (by its path, a.b) read from the key the map gives for it
pretty(a) -> String where a: EncodePretty-print value as JSON
stringify(a) -> String where a: EncodeSerialize value as compact JSON

Errors

Every fallible json.* call returns Result(T, JsonError). The JsonError enum has four variants you can pattern-match on, or fall back to show it with "{e}" when you just want a rendered string:

VariantFieldsMeaning
Syntax(msg, offset, line, column)String, Int, Int, IntMalformed JSON, offset being the 0-based byte of the text where reading stopped (the text’s length when it ends too soon)
TypeMismatch(expected, actual, offset, line, column)String, String, Int, Int, IntA value’s JSON type did not match the type it decodes into, or a number the type cannot hold (1e400, beyond Float’s range: a number out of Float's range; for an Int, a number out of Int's range); actual ends with the value’s path, offset is the byte where the value starts
MissingField(name, offset, line, column)String, Int, Int, IntA required (non-Option) field was absent; name is its path, offset the byte where the object it is missing from starts
Other(msg, offset, line, column)String, Int, Int, IntAnything else: a tuple’s array of the wrong length, a date that is none, a value too deep for json.decode; offset is the byte where the value starts

An error about a value of the document ends with the path of that value: the fields of a record and the keys of a map by name (inner.a), a key that is not made of ASCII letters, digits, _ and - as a JSON string in brackets (tags["a b"]), and the elements of a list or a tuple by index (xs[1]; [2] for an element of a list the document is). TypeMismatch("Int", "string at inner.a", ..) reads json type mismatch at line <line>, column <column>: expected Int, got string at inner.a; a missing field is MissingField("inner.a", ..); an Other about a value (a tuple of the wrong length, a date that is none) ends with at <path>. An error about the document itself, such as a Syntax error or an array where a record is expected, has no path.

Every error says where in the text its value is, in its last three fields: the 0-based byte offset, and its line and column, both counted from 1, the column in characters (as silt’s own errors count them). Syntax is where reading stopped, the others where the value starts (for MissingField, the object the field is missing from; the start of the document for the document). A Syntax, a TypeMismatch and a MissingField show the line and the column (json type mismatch at line 3, column 11: expected List, got number at tags), an Other shows its message alone; the byte is for a program that cuts the text. json.decode reads no text: its errors’ offset, line and column are 0, and they show no place (json type mismatch: expected Int, got string at x). A json.Decode impl’s error is placed at the part the impl was given, whatever place the impl wrote (write 0, 0, 0). A byte order mark before the document is counted in the byte, and is no column.

See stdlib errors for how every error enum is shown.

Decodable types

The type argument of json.parse, json.parse_with and json.decode names the type to decode into:

FunctionType argument
json.parseInt, Float, String, Bool, json.Value, a record type, an enum type, a type with a json.Decode impl, or List(T), Option(T), Map(String, T) or a tuple of decodable types
json.parse_withInt, Float, String, Bool, json.Value, a record type, an enum type, a type with a json.Decode impl, or List(T), Option(T), Map(String, T) or a tuple of decodable types
json.decodeInt, Float, String, Bool, json.Value, a record type, an enum type, a type with a json.Decode impl, or List(T), Option(T), Map(String, T) or a tuple of decodable types

A type argument is written in full, at any depth: json.parse(text, List(User)), json.parse(text, (Int, String)), json.parse(text, Map(String, List(Int))). Its parts are decoded as the fields of a record are (below). An alias of any of these is the type it names (type Member = User, then json.parse(text, Member)).

The fields of a record type, and of each variant of an enum type (and of every record and enum type nested in them), may have these types:

  • Int, Float, String, Bool
  • time.Date, time.Time, time.DateTime
  • url.Url, a string that url.parse reads (an error names what is wrong, not the text)
  • time.Instant and time.Duration, as json.stringify writes them: {"epoch_ns": n}, {"ns": n}
  • json.Value, which keeps that part of the document as it is
  • List(T), Option(T), Map(String, T)
  • tuples, such as (Int, String)
  • record types, a generic one with its type arguments (Box(Int))
  • enum types, a generic one with its type arguments (see Enums)
  • type aliases of any of these

where T is again one of these types. Anything else (a Set, a generic record or enum without its type arguments, a builtin enum such as time.Weekday, a function, a Map whose key is not String, a type parameter) has no decoder.

An Option directly inside an Option (Option(Option(Int)), at any depth, also through an alias or a generic type’s argument) has no decoder either: None and Some(None) are both written as null, so Some(None) would never read back. Option(json.Value) is decoded: there a null reads as None, not as Some(json.Null).

A type whose fields give a generic type ever larger type arguments made of its own (type T(a) { kids: List(T(List(a))) }) has no decoder: it grows with every level. Fields that hold it at larger arguments it writes out (f: Option(T(W(Int)))) do not make it grow, nor do types that each give another one other arguments (R1 { w: W(R2) }, …, R8 { w: W(W(Int)) }); a parameter that comes back to its own place inside another type (f: Option(T(List(a), Option(a))) of T(a, b)) does. Nor is a type decoded that has, in a field (its own, or one of a type nested in it), a record or enum type whose type arguments are nested more than 32 levels deep or hold more than 4,096 types: W written 34 times around Int is refused, 33 times is decoded (its field holds W 32 times); nor one that holds more than 4,096 types at their arguments in all (types whose fields each hold the next at two other arguments, l: T1(L(a)) and r: T1(R(a)), make twice as many with every level, though none grows and none is deep). The type given to the decoder is not counted itself. A field of type json.Value can hold such a part, to be decoded on its own.

The checker refuses such a type where it is written at the call (json.parse(text, T(Int))), with the types of the fields under it. One that reaches a decoder through a function or a bound (load(text, T(Int)) of a load that hands its type to json.parse, also a function that calls itself with its type wrapped once more each round) is refused when the program decodes: the decoder returns Err(Other(..)) before it reads the document, naming the field, its type (a run of one type written once with its count, W^32(Int)) and the limit:

cannot decode field `x` of `Page`: its type N(W^32(Int)) is nested too deeply: a decoder reads type arguments 32 levels deep and 4,096 types in all

A type that reaches a decoder in the body of a generic json.Decode impl (json.decode(value, Page(a)) of trait json.Decode for Box(a), given Box(W(...))) is refused by that decoder when the document reaches the impl’s part: the Err then ends with the part’s path (at [0]), and a document that never reaches it ([] of a List(Box(..))) decodes.

The check follows a type into a trait method also where the call goes through a bound (where a: Reader, then Reader.get(r, s, t)): an impl that decodes its type parameter inside an Option (json.parse(s, Option(t)), a field v: Option(t)), given an Option that way, is refused where the use gives that Option, as the same call on the known type, Reader.get(R { tag: 1 }, "null", Option(Int)), is: the error names the decoded type and the field the Option in an Option is in.

A number of the document goes into an Int when it is a whole number in Int’s range (1, 1.0, 1e3). A number with a fraction (1.5), or one out of that range, is Err(TypeMismatch("Int", ..., ..)): nothing is cut off or rounded. json.decode reads a json.Value’s numbers as json.parse holds them: a json.Int goes into an Int, and a json.Float into no Int, whatever its value (json.decode(json.Float(2.0), Int) is an Err), so a value decodes as the text it was read from does.

These are the types that have json.Decode, which the four functions need of their type argument. A type is checked where it is known: written at the call (json.parse(text, Config)), held in a variable, given to a decoder used as a value, or given to a function or method that passes it on to the decoder (fn load(text, type a) where a: json.Decode { json.parse(text, a) }: each call of load is checked, and the error notes that load passes it to json.parse). A record with a field no decoder exists for is a compile error that names the field and its type, and so is an enum with a variant whose field has none (the error names the variant); so is a generic record or enum without its type arguments (json.parse(text, Box)), or a type the function does not take (such as json.parse(text, Set(Int)), or json.parse(text, List), whose argument is left open), and so is a list, an option, a map or a tuple with a part that has no decoder (json.parse(text, List(Set(Int)))). The check applies equally to a decoder imported by name (import json.{ parse }) and to one called through a module alias, and a type is refused whatever a document would hold (an Option field whose key is left out, another variant of the enum, an empty list or map too).

Enums

An enum type the program declares, without type parameters, is decoded from what json.stringify writes of a variant, so a variant written with json.stringify reads back as the same variant:

VariantJSON
without fields, Active"Active"
with fields, Moved("x", Some(2)){"fields":["x",2],"variant":"Moved"}

A variant without fields is the string of its name, wherever it is (in a record, a list, a map, the fields of another variant). Of a variant with fields, "variant" names the variant and "fields" lists its fields in the order the variant declares them, each decoded as a record field of its type is (a record, a list, an option, another enum); other keys of the object are ignored.

An enum type may be decoded at the top (json.parse(text, Status)), as the elements of a list and the values of a map, and as the type of a field anywhere in a record or in another enum’s variant. A document that is no variant of the enum is an Err, which ends with the path, as the error of a record does (here of an enum at the top):

DocumentError
a string the enum has no variant ofOther("`Status` has no variant `Gone`", ..)
the name of a variant with fieldsOther("variant `Paused` of `Status` has 1 field, got 0", ..)
no string and no object (a number, an array)TypeMismatch("String or object", "number", ..)
an object that names a variant without fieldsTypeMismatch("String", "object", ..)
an object without a "variant" keyMissingField("variant", ..)
an object without a "fields" keyMissingField("fields", ..)
a "variant" that is no stringTypeMismatch("String", "number at variant", ..)
a "variant" the enum has no variant ofOther("`Status` has no variant `Gone` at variant", ..)
"fields" that is no arrayTypeMismatch("array", "number at fields", ..)
the wrong number of fieldsOther("variant `Paused` of `Status` has 1 field, got 2 at fields", ..)
a field of the wrong typethe error of a value of that type, such as TypeMismatch("Int", "string at fields[0]", ..)
import json

type Status {
  Active,
  Paused(Int),
}

type Job {
  name: String,
  status: Status,
}

fn main() {
  let job = Job { name: "build", status: Paused(3) }
  let text = json.stringify(job)
  println(text) -- {"name":"build","status":{"fields":[3],"variant":"Paused"}}
  println(json.parse(text, Job)) -- Ok(Job { name: "build", status: Paused(3) })
  println(json.stringify([Active, Paused(1)])) -- ["Active",{"fields":[1],"variant":"Paused"}]
  println(json.parse("""{"name": "x", "status": "Gone"}""", Job))
  -- Err(`Status` has no variant `Gone` at status)
}
open in playground

The toml decoders read an enum in the same forms (see toml).

Nesting limits

json.stringify and json.pretty write a value nested up to 1,000 levels deep. The element of a list or of a tuple, the field of a record or of an enum variant and the value of a map are each one level further in than what holds them; the content of a Some is not (it is written in the Some’s place). A value nested deeper is a runtime error:

json.stringify: the value is nested more than 1000 levels deep

The parser stops sooner: json.parse reads a document whose arrays and objects are nested up to 127 levels deep, and give a Syntax error (recursion limit exceeded) for one nested deeper. A value written at more levels than that is valid JSON that silt itself does not read back.

json.decode reads a json.Value nested up to 1,000 levels deep, counted as for json.stringify; one nested deeper is an Err(Other(msg, ..)):

json.decode: the value is nested more than 1000 levels deep

json.Value

type Value {
  Null,
  Bool(Bool),
  Int(Int),
  Float(Float),
  String(String),
  Array(List(Value)),
  Object(Map(String, Value)),
}

A JSON document as it is, for input whose shape is not known in advance: any document reads into it. Its variants are written through the module, json.Null, json.Int(n), json.Object(fields). When the shape is known, decode into a record type instead: a mistake in the document is then an error where it is read.

  • A number is an Int when it is a whole number in Int’s range (1, 1.0, 1e3), as for an Int field, and a Float otherwise (1.5, a number out of that range). A number beyond Float’s range (1e400) is none: a TypeMismatch where it starts.
  • An object is a Map(String, Value). Its keys come out sorted, not in the document’s order, and of a key written twice the last value counts; a value that is no json.Value is the error all the same, the first in the document’s order.

json.stringify and json.pretty write a json.Value as the JSON it holds: json.Int(1) as 1, json.Object as an object.

import json
import map

fn name_of(body: String) -> Option(String) {
  match json.parse(body, json.Value) {
    Ok(json.Object(fields)) -> match map.get(fields, "name") {
      Some(json.String(name)) -> Some(name)
      _ -> None
    }
    _ -> None
  }
}

fn main() {
  println(name_of("""{"name": "Ada", "age": 36, "tags": ["x"]}""")) -- Some("Ada")
  let reply = json.Object(#{ "name": json.String("Ada"), "age": json.Int(36) })
  println(json.stringify(reply)) -- {"age":36,"name":"Ada"}
}
open in playground

A record field of type json.Value keeps that part of the document as it is, for json.decode to read once its shape is known. Like any field that is no Option, it must be in the document (a JSON null is json.Null); a field of type Option(json.Value) may be left out, and there a null reads as None.

json.Encode

trait Encode {
  fn encode(self) -> Value
}

What json.stringify and json.pretty need of the value they write. A type has it by its structure, as it has Display: Int, Float, String, Bool, (), a json.Value, a Date, a Time and a DateTime have it; a list, a tuple, an Option and a record or enum type (the program’s or a builtin module’s) have it when their parts do; a map when its values do (a key is written as its text). Bytes, a set, a function, a channel and a handle have none. A function that hands a value of a type variable to json.stringify says so, as for Display; one without annotations is inferred to need it. As for Display, a type that holds more than 4,096 types at their arguments is refused:

import json

fn send(x: a) -> String where a: json.Encode {
  json.stringify(x)
}

fn main() {
  println(send([1, 2])) -- [1,2]
}
open in playground

Without the where clause the definition is an error:

type variable `a` is not known to implement trait 'json.Encode', which 'json.stringify' needs

A program names the trait with its module, json.Encode.

Write trait json.Encode for T to replace the structural form of T, in the module that declares T (as a Display impl is written; an impl for a builtin type is an error, a builtin type keeps its own form). Its encode gives the json.Value the type is written as, wherever a value of the type is inside what is written: at the top, in a list, as a map’s value, in a record’s or a variant’s field. A Some around it stays structural (Some(x) is written as x is), and a type that holds a function may have a written impl. An impl for a generic type is allowed; what it asks of the type’s arguments it says in a where clause.

import json

type Money {
  cents: Int,
}

trait json.Encode for Money {
  fn encode(self) -> json.Value {
    json.Int(self.cents)
  }
}

type Order {
  id: Int,
  total: Money,
}

fn main() {
  println(json.stringify(Order { id: 7, total: Money { cents: 1250 } }))
  -- {"id":7,"total":1250}, not {"id":7,"total":{"cents":1250}}
}
open in playground

json.Decode

trait Decode {
  fn decode(value: Value) -> Result(Self, JsonError)
}

What json.parse and json.decode need of the type they decode into. A type has it by its structure: the types of Decodable types have it, a record or enum type of the program when the types of its fields do, and a generic one at its type arguments when the types of its fields do with the arguments in their places (Box(Int) of type Box(a) { v: a }; json.parse(text, Box(a)) in a function with where a: json.Decode). A date and a time are decoded as the type of a field or of a part of a list, an option, a map or a tuple, not as the type a decoder is given. A function with a type a parameter (any annotation names the variable) that hands it to a decoder writes where a: json.Decode; only a function with no annotation at all (fn load(text, t) { json.parse(text, t) }) is inferred to need it:

import json

type Config {
  port: Int,
}

fn load(text: String, type a) -> Result(a, json.JsonError) where a: json.Decode {
  json.parse(text, a)
}

fn main() {
  println(load("""{"port": 80}""", Config)) -- Ok(Config { port: 80 })
}
open in playground

Without the where clause the definition is an error:

type variable `a` is not known to implement trait 'json.Decode', which 'json.parse' needs

A type that lacks it is refused at the call that gives it, as a decoder refuses it, with the function that passes it on in a note:

`json.parse` cannot decode `Holder`: field `s` has type `Set(Int)`, which has no decoder
  = note: `load` passes it to `json.parse`

A type past the limits of what a decoder reads (see Decodable types) given that way is not refused at the call: the decoder a function or a bound hands it to returns its Err before it reads the document, and the decoder in a generic impl’s decode returns it when the document reaches the impl’s part.

Write trait json.Decode for T to replace the structural form of T, in the module that declares T (as a json.Encode impl is written; an impl for a builtin type is an error, a builtin type keeps its own form). An impl for a generic type is allowed; it decodes a part of a type argument a with a.decode(v), which its where clause allows: trait json.Decode for Box(a) where a: json.Decode. An impl may be for an instantiation, trait json.Decode for Box(Int), beside impls for others; a type with no impl among them (Box(Bool)) is refused, at the top or in a field. The same holds of an impl of a program’s trait for a generic type whose where clause asks json.Decode of each type parameter: of trait Dec: json.Decode, trait Dec for Box(a) where a: json.Decode decodes at the type the use gives (Self in a default method is Box(Int)), and a method of such an impl may call a.decode(v) or name the type at its parameters, json.decode(v, Box(a)). Its decode gives the value of T that a json.Value is, wherever a value of the type is in the document: at the top, as an element of a list or a value of a map, in a record’s or a variant’s field, in a list or a map in one. The fields of T are then not looked into, so T may hold a type no decoder has. An Option around it stays structural (null is None). The Err it returns is the decoder’s error, with the path of its part appended as to the decoder’s own errors: Other("bad tags", ..) at posts[1].tags is Other("bad tags at posts[1].tags", ..), a MissingField("name", ..) there is MissingField("posts[1].tags.name", ..). A message is the impl’s text, and the path is appended to it as it is: an error the impl got from json.decode of a part of its value, TypeMismatch("Int", "string at k", ..), ends with at k at posts[1].tags. The first error counts, the impl’s or the decoder’s: a record’s errors in the order its type declares the fields, a map’s in the sorted order of its keys; a syntax error anywhere in the text wins. The toml decoders and a postgres row honour the impl too (see toml and postgres).

import json
import list
import set

type Tags {
  names: Set(String),
}

trait json.Decode for Tags {
  fn decode(value: json.Value) -> Result(Self, json.JsonError) {
    match value {
      json.String(text) -> Ok(Tags { names: set.from_list([text]) })
      json.Array(items) -> {
        let names = list.filter_map(items) { item ->
          match item {
            json.String(name) -> Some(name)
            _ -> None
          }
        }
        Ok(Tags { names: set.from_list(names) })
      }
      _ -> Err(json.Other("tags are a string or a list of strings", 0, 0, 0))
    }
  }
}

type Post {
  title: String,
  tags: Tags,
}

fn main() {
  println(json.parse("""{"title": "a", "tags": "x"}""", Post))
  -- Ok(Post { title: a, tags: Tags { names: #[x] } })
  println(json.parse("""{"title": "a", "tags": 3}""", Post))
  -- Err(tags are a string or a list of strings at tags)
}
open in playground

T.decode(value) decodes a json.Value into T: by its impl where one is written, else as json.decode(value, T) does. For a type a with the bound, a.decode(value); in a default method of a trait that has json.Decode among its supertraits, Self.decode(value). A generic type is written with its arguments, Box(Int).decode(value). It takes no value of the type: x.decode(..) on a value is no call of it.

json.decode

json.decode(value: Value, type a) -> Result(a, JsonError) where a: Decode

Decodes a json.Value into the type a, as json.parse decodes the same document as text, with the same errors.

import json

type Event {
  kind: String,
  data: json.Value,
}

type Resize {
  width: Int,
  height: Int,
}

fn describe(text: String) -> Result(String, json.JsonError) {
  let event = json.parse(text, Event)?
  match event.kind {
    "resize" -> {
      let size = json.decode(event.data, Resize)?
      Ok("resize to {size.width}x{size.height}")
    }
    _ -> Ok("ignored {event.kind}")
  }
}

fn main() {
  println(describe("""{"kind": "resize", "data": {"width": 3, "height": 4}}"""))
  -- Ok(resize to 3x4)
}
open in playground

json.encode

json.encode(value: a) -> Value where a: Encode

The json.Value of what json.stringify writes of a value: what json.parse reads of that text. A whole number is a json.Int (1.0 too), a record and a map are a json.Object, whose keys come out sorted (so json.stringify(json.encode(r)) writes a record’s fields in the order of their names, json.stringify(r) in the order its type declares them), a None and () are json.Null. Written json.Encode impls are used wherever their types are in the value, at the top too: the counterpart of json.decode. An impl’s encode uses it for the parts it writes; for its own value (json.encode(self)) it would call itself without end. json.Encode.encode(x) is the method of the trait, called through it in a module that imports json: on a value whose type has a written impl it is what the impl gives, as it gives it (json.Float(1.0) stays a Float); on any other value it is json.encode(x).

import json

type Pair {
  left: Int,
  right: Int,
}

trait json.Encode for Pair {
  fn encode(self) -> json.Value {
    json.Array([json.encode(self.left), json.encode(self.right)])
  }
}

fn main() {
  println(json.encode([1, 2])) -- Array([Int(1), Int(2)])
  println(json.stringify(Pair { left: 1, right: 2 })) -- [1,2]
}
open in playground

json.parse

json.parse(s: String, type a) -> Result(a, JsonError) where a: Decode

Parses a JSON string into a value of type a. The type is passed as a type parameter (see Generics — not a string), written in full: json.parse(text, User), json.parse(text, List(Point)) for an array, json.parse(text, Map(String, Int)) for an object read as a map. Fields are matched by name; Option fields default to None if missing from the JSON. A key that no field names is skipped, in a record at any depth (a JSON document mostly comes from a program, which may add fields over time; toml.parse refuses such a key), so a misspelled key is no error: the field it was meant for is missing, an Err(MissingField(...)), or None for an Option field. A field may be named by a keyword, so the key "type" is read into the field of type Event { type: String } (see Types). A key no field can be named after ("Name", "userId") is read by json.parse_with. One UTF-8 byte order mark (U+FEFF) before the document, which files written by Windows tools often start with, is dropped, as toml.parse and csv.parse drop it; the byte of a Syntax error is still counted from the start of the text, the mark included.

import json

type Inner {
  n: Int,
}

type Out {
  name: String,
  inner: Inner,
  nick: Option(String),
}

fn main() {
  -- "nikc" and "m" name no field: skipped
  let text = """{"name": "Ann", "nikc": "A", "inner": {"n": 1, "m": 2}}"""
  println(json.parse(text, Out)) -- Ok(Out { name: "Ann", inner: Inner { n: 1 }, nick: None })
  println(json.parse("""{"nmae": "Ann", "inner": {"n": 1}}""", Out)) -- Err(json missing field at line 1, column 1: name)
}
open in playground

Fields of type Date, Time, and DateTime (from the time module) are automatically parsed from ISO 8601 strings. DateTime fields also accept timezone-aware formats (RFC 3339) — the offset is applied and the value is stored as UTC:

Field typeAccepted formatsExample
DateYYYY-MM-DD, a year of more digits or with a sign as silt shows it (12026-01-01, -001-01-01)"2024-03-15"
TimeHH:MM:SS, HH:MM, HH:MM:SS.fffffffff"14:30:00", "14:30:00.25"
DateTimeYYYY-MM-DDTHH:MM:SS, YYYY-MM-DDTHH:MM, a fractional second, with optional Z or ±HH:MM offset; the year as for Date"2024-03-15T09:00:00+09:00"

A value that is no string is a TypeMismatch that names the field’s type, as for an Int field: {"d": 1} for a Date field d is Err(TypeMismatch("time.Date", "number at d", ..)).

A fractional second is read to the nanosecond; further digits are cut. A second 60, a leap second, is no time silt holds: it is refused with an Other that names the text, such as invalid time '23:59:60': a leap second (second 60) is not read. So is any text written as a date, a time or a date and time (in a form of the table) whose field is out of its range, which says the field: invalid date '2026-13-01': the month is out of range, invalid datetime '2026-02-30T10:00:00Z': the day is out of range: February 2026 has 28 days. A date or a time of day not written so says how one is written, whatever its fields hold: invalid date '11-23-2026' (expected YYYY-MM-DD): input is out of range, invalid time '930' (expected HH:MM:SS): ...; a date and time not written so is invalid datetime '<text>'.

import json

type User {
  name: String,
  age: Int,
}

fn main() {
  let input = """{"name": "Alice", "age": 30}"""
  match json.parse(input, User) {
    Ok(user) -> println(user.name)
    Err(e) -> println("Error: {e}")
  }
}
open in playground

Date/Time example:

import json
import time

type Event {
  name: String,
  date: time.Date,
}

fn main() -> Result((), json.JsonError) {
  let e = json.parse("""{"name": "launch", "date": "2024-03-15"}""", Event)?
  println(e.date |> time.weekday) -- Friday
  Ok(())
}
open in playground

json.parse_with

json.parse_with(s: String, keys: Map(String, String), type a) -> Result(a, JsonError) where a: Decode

Parses a JSON document as json.parse does, but each field that keys names is read from the key the map gives for it: #{"user_id": "userId"} reads the field user_id from the key userId. A field the map does not name is read from the key of its own name, as json.parse reads it. This reads a key that can never be a field’s name: a capital letter (Name), camelCase (userId), a - (default-features). Keys are still matched exactly, the map’s as the fields’ own; it is the same map csv.parse_with takes for columns.

A field of a nested record is named by its path of fields from the type given, each field’s name and not its key: #{"owner.user_id": "userId"} for the field user_id of the record in the field owner. A list, an Option, a map, a tuple or a variant on the way adds nothing to the path: the records of tags: List(Tag) have their fields at tags.label, the same key for every element. An entry holds at its path and at every depth below it where the same type comes again inside itself: for type Node { label: String, kids: List(Node) }, #{"label": "Label"} reads Label in every node of the tree, and #{"val.user_id": "uid"} reads uid in the user of every node of type Tree { val: User, kids: List(Tree) }, where the type that comes again is the one above val. A longer entry of the same field wins below its own path (kids.label for every node but the top), and one type at two places that are not inside each other keeps an entry for each (author.name holds for the author, not the editor). The map reaches no field of a type with a json.Decode impl, which decodes its part itself: an entry whose path goes into such a type is a runtime error (json.parse_with: the map names the field `tags.names`, and Tags decodes itself with its json.Decode impl); the field that holds it may be given a key.

A key of the map that is no path of a field of the type is a runtime error (json.parse_with: the map names the field `tags.lable`, and User has no field at that path), and so is a map that gives one key to two fields of a record (“json.parse_with: the map reads the fields a and b of Two from one key, b```): the map is the program's, not the document's. An error names the key as the document writes it (Err(json missing field at line 1, column 1: userId)). Everything else is as for json.parse. json.stringify` writes each field under its own name.

import json

type Owner {
  name: String,
  user_id: Int,
}

type Repo {
  full_name: String,
  owner: Owner,
}

fn main() {
  let text = """{"fullName": "a/b", "owner": {"Name": "Ann", "userId": 7}}"""
  let keys = #{ "full_name": "fullName", "owner.name": "Name", "owner.user_id": "userId" }
  println(json.parse_with(text, keys, Repo)) -- Ok(Repo { full_name: "a/b", owner: Owner { name: "Ann", user_id: 7 } })
  println(json.parse(text, Repo)) -- Err(json missing field at line 1, column 1: full_name)
}
open in playground

json.pretty

json.pretty(value: a) -> String where a: Encode

Serializes a value to a pretty-printed JSON string (with indentation and newlines). It writes and refuses the same values as json.stringify.

import json

fn main() {
  let data = #{ "name": "silt", "version": "1.0" }
  println(json.pretty(data))
}
open in playground

json.stringify

json.stringify(value: a) -> String where a: Encode

Serializes a value to a compact JSON string. Each kind of value is written as follows:

ValueWritten as
Int, Float, String, Boola number, a string, true or false
List(a), a tuplean array: (1, "a") is [1,"a"]
Map(k, v)an object; a key that is no String is written as its shown text (the Float key 1.0 reads "1.0"); a string inside a key is quoted (["a", "b"] reads "[\"a\", \"b\"]"); two keys shown as one text (two Bytes longer than the 32 bytes their text shows, alike in those) are a runtime error, json.stringify: two keys of a map show as the same text: bytes(...) (in json.encode too)
a recordan object of its fields, in the order the type declares them: {"name":"Ada","age":36}
Some(x)x, as x is written
None, ()null
any other variant (of Result too){"fields":[...],"variant":"Name"}; a variant without fields is the string "Name"
json.Valuethe JSON it holds: json.Int(1) is 1, json.Null is null
Date, Time, DateTimethe text silt shows of them: "2026-10-19", "12:30:00" (with a fractional second only when the value has one: "12:30:00.250") and "2026-10-19T12:30:00"
Duration, Instantas the records they are: {"ns":2000000000}, {"epoch_ns":...}

The keys of a map, and so of a json.Object, are written in sorted order; the fields of a record in the order its type declares them. json.parse reads a Date, a Time, a DateTime, an Instant and a Duration back into a field of the same type, a record into its record type, and a variant into its enum type when the program declares it (see Enums); a variant of a builtin enum and () are written but not read back.

json.stringify and json.pretty write the same values: those of a type that has json.Encode. A type with no json form is a compile error that names the way down to the part that has none, wherever in the value it is: Bytes, a Set, a function (the constructor of a variant, such as Some, is one), a channel, a task handle, a TCP listener or stream.

type 'List(Reply)' does not implement trait 'json.Encode': element > field 'body' is of type 'Bytes', which does not implement trait 'json.Encode'

To send bytes as JSON, turn them into text first (bytes.to_string, bytes.to_hex or bytes.to_base64); to send a set, make a list of it (set.to_list).

import json
import time

fn main() {
  let data = #{ "key": [1, 2, 3] }
  println(json.stringify(data))
  -- {"key":[1,2,3]}
  println(json.stringify(#{ 1.0: "one" })) -- {"1.0":"one"}
  println(json.stringify(time.Date { year: 2026, month: 10, day: 19 }))
  -- "2026-10-19"
}
open in playground