Skip to content

Json.encode ​

ant
func Json.encode[T](t: Reflect.Type[T], value: T, indent: string = ""): string

Json.encode returns the JSON text of value as t describes it, which Json.decode at t reads back. It writes what Json.stringify writes, except that a record in a union of two or more records is written with its name, as {"Circle":{"radius":1.0}}, or as "Empty" when it has no fields. The type comes first so that it fixes T before value is checked against it. indent is as for Json.stringify.

It panics where Json.decode does on t, and where Json.stringify does on value.

Details ​

  • Every field is written, in declaration order, including one that is null or equal to its default.
  • Each panic message starts Json.encode: .

Basic examples ​

ant
type Server = { host: string, port: int = 8080 }

Json.encode(type(Server), Server{ host: "a.example" }) // "{\"host\":\"a.example\",\"port\":8080}"
Json.encode(type(Array[int | null]), [1, null])        // "[1,null]"

Pass indent to spread the text over lines:

ant
type Server = { host: string, tags: Array[string] }

println(Json.encode(type(Server), Server{ host: "a", tags: ["eu"] }, indent: "  "))
text
{
  "host": "a",
  "tags": [
    "eu"
  ]
}

Scope ​

Numbers are written as String.from writes them: an integer in full, a float with .0 when it is integral:

ant
Json.encode(type(int), 9007199254740993)       // "9007199254740993"
Json.encode(type(Array[float64]), [1.0, 1e21]) // "[1.0,1e+21]"

A map is an object, its entries in order. A key that is a named primitive is written without its tag:

ant
type UserId = string

Json.encode(type(Map[UserId, int]), Map{ UserId("u-1"): 10, UserId("u-2"): 7 }) // "{\"u-1\":10,\"u-2\":7}"

A record in a union of records is written under its name, and one with no fields as its name alone:

ant
type Circle = { radius: float64 }
type Square = { side: float64 }
type Empty = {}
type Shape = Circle | Square | Empty

let shapes: Array[Shape] = [Circle{ radius: 2.0 }, Empty{}]
Json.encode(type(Array[Shape]), shapes) // "[{\"Circle\":{\"radius\":2.0}},\"Empty\"]"
Json.encode(type(Array[Shape]), [])     // "[]"

The slot's type decides, not the value. The same Circle is bare where nothing else could be there:

ant
type Circle = { radius: float64 }
type Square = { side: float64 }

Json.encode(type(Circle), Circle{ radius: 2.0 })          // "{\"radius\":2.0}"
Json.encode(type(Circle | null), Circle{ radius: 2.0 })   // "{\"radius\":2.0}"
Json.encode(type(Circle | Square), Circle{ radius: 2.0 }) // "{\"Circle\":{\"radius\":2.0}}"

An enumeration is written as its names:

ant
type Debug = {}
type Info = {}
type Config = { name: string, level: Debug | Info = Info{} }

Json.encode(type(Config), Config{ name: "app" }) // "{\"name\":\"app\",\"level\":\"Info\"}"

A prelude record is written under its declared name, with its owner where it has one: Ok and Err alone, Error.NotExist with Error:

ant
let failed: Result[int, Error] = Result.err(Error{ message: "gone", kind: Error.NotExist{} })
Json.encode(type(Result[int, Error]), failed) // "{\"Err\":{\"error\":{\"message\":\"gone\",\"kind\":\"Error.NotExist\"}}}"

Named primitives, sets, time values, and patterns are written as Json.stringify writes them:

ant
type UserId = string
type Login = { user: UserId, at: Time.Instant, roles: Set[string] }

let login = Login{ user: UserId("u-1"), at: Time.parseInstant("2026-11-28T09:00:00Z").unwrap(), roles: Set.of(["admin"]) }
Json.encode(type(Login), login) // "{\"user\":\"u-1\",\"at\":\"2026-11-28T09:00:00Z\",\"roles\":[\"admin\"]}"

A Json.Raw is written as its tokens, with the white space of the output:

ant
type Event = { type: string, data: Json.Raw }

Json.encode(type(Event), Event{ type: "n", data: Json.Raw(`{ "value" : 1 }`) }) // "{\"type\":\"n\",\"data\":{\"value\":1}}"

Named arguments ​

indent is a string of spaces and tabs written once per level:

ant
Json.encode(type(Array[int]), [1, 2], indent: "\t") // "[\n\t1,\n\t2\n]"
Json.encode(type(Array[int]), [1], indent: "-")     // panic: Json.encode: the indent must be spaces and tabs, got "-"

Applications ​

Save state that the program reads back at the same type:

ant
type Todo = { title: string, done: bool = false }
type Event = { at: int, change: Added | Removed }
type Added = { todo: Todo }
type Removed = { title: string }

let t = type(Array[Event])
let log: Array[Event] = [
  Event{ at: 1, change: Added{ todo: Todo{ title: "milk" } } },
  Event{ at: 2, change: Removed{ title: "milk" } },
]
let text = Json.encode(t, log)
println(text)
println(Json.decode(text, t).unwrap() == log)
text
[{"at":1,"change":{"Added":{"todo":{"title":"milk","done":false}}}},{"at":2,"change":{"Removed":{"title":"milk"}}}]
true

Save and load a value of any type, passing the type along from a generic function:

ant
type Todo = { title: string, done: bool = false }

func save[T](path: string, t: Reflect.Type[T], value: T): Result[void, Error] {
  File.write(path, Json.encode(t, value, indent: "  ") + "\n")
}

func load[T](path: string, t: Reflect.Type[T]): Result[T, Error] {
  let text = try File.read(path)
  Json.decode(text, t) | Result.wrapErr(path)
}

let t = type(Array[Todo])
save("todos.json", t, [Todo{ title: "milk" }]).unwrap()
print(File.read("todos.json").unwrap())
println(load("todos.json", t))
text
[
  {
    "title": "milk",
    "done": false
  }
]
Ok{ value: [Todo{ title: "milk", done: false }] }

Properties and relations ​

Json.decode at the same type reads the text back to a value == to the one written, except for a Time.Duration and a Json.Raw:

ant
type Circle = { radius: float64 }
type Empty = {}

let t = type(Array[Circle | Empty | null])
let v: Array[Circle | Empty | null] = [Circle{ radius: 1.5 }, Empty{}, null]
assert(Json.decode(Json.encode(t, v), t).unwrap() == v)

Where the type reaches no union of two or more records, the text is what Json.stringify writes:

ant
type Server = { host: string, port: int | null }

let s = Server{ host: "a", port: null }
assert(Json.encode(type(Server), s) == Json.stringify(s))

Possible issues ​

The type comes first, so a pipe cannot pass the value in. Call Json.encode with both:

ant
let xs = [1, 2]
println(xs | Json.encode(type(Array[int])))
// error: cannot use Array[int] where Reflect.Type[T] is expected

A type with no JSON form panics, whatever the value:

ant
type Upload = { name: string, data: Bytes }

Json.encode(type(Upload), Upload{ name: "a", data: "hi".toBytes() }) // panic: Json.encode: Upload.data: Bytes has no JSON form
Json.encode(type(Map[int, string]), Map{ 1: "a" })
// panic: Json.encode: Map[int, string] has no JSON form: a JSON name is a string, and int is not

A union of two or more records takes strings and objects, so it holds no other member that reads either:

ant
type Circle = { radius: float64 }
type Square = { side: float64 }

Json.encode(type(Circle | Square | string), "x") // panic: Json.encode: Circle | Square | string: Circle and string are both read from a JSON string

Adding a second record to a union changes how the first is written, so text written before the change no longer reads:

ant
type Circle = { radius: float64 }
type Square = { side: float64 }

let old = Json.encode(type(Circle | null), Circle{ radius: 1.0 })
old                                            // "{\"radius\":1.0}"
Json.decode(old, type(Circle | Square | null)) // Err{ error: Error{ message: "$: Circle | Square | null has no member named \"radius\" at line 1, column 2", kind: null } }

Giving a field to a member with no fields changes how it is written too, from its name to an object. Text written before still reads when the new field has a default:

ant
type Start = { urgent: bool = false }
type Stop = {}
type Command = Start | Stop

Json.encode(type(Command), Start{})   // "{\"Start\":{\"urgent\":false}}"
Json.decode(`"Start"`, type(Command)) // Ok{ value: Start{ urgent: false } }

A reader that takes every number as a float64, as JavaScript and Json.parse do, rounds an integer above 2^53. Write such an id into a string field for those readers:

ant
type Order = { id: int }

let text = Json.encode(type(Order), Order{ id: 9007199254740993 })
text             // "{\"id\":9007199254740993}"
Json.parse(text) // Ok{ value: Map{ "id": 9007199254740992.0 } }

A Json.Raw must hold one JSON value:

ant
Json.encode(type(Json.Raw), Json.Raw("{")) // panic: Json.encode: Json.Raw is not JSON: unexpected end of JSON input

NaN and the infinities have no JSON form:

ant
Json.encode(type(float64), 0.0 / 0.0) // panic: Json.encode: NaN has no JSON form
Json.encode(type(float64), 1.0 / 0.0) // panic: Json.encode: Infinity has no JSON form

A value that contains itself has no JSON form:

ant
type Node = { name: string, next: Node | null = null }

let a = Node{ name: "a" }
a.next = a
println(Json.encode(type(Node), a)) // panic: Json.encode: cyclic value

A Time.Duration reads back with its fraction spread, so it is not == to the one written:

ant
let d = 1500ms
let text = Json.encode(type(Time.Duration), d)
println(text)
println(Json.decode(text, type(Time.Duration)).unwrap() == d)
text
"PT1.5S"
false

Compare durations with Time.compareDuration.

See also ​

Json.decode · Json.stringify · Json.Raw · type · Unions