# Json.decode

```ant
func Json.decode[T](text: string, t: Reflect.Type[T], rejectUnknown: bool = false): Result[T, Error]
```

Json.decode reads JSON text into a value of the type t names, so Json.decode(text, type(Config))
reads a Config. The result is Ok of the value, or Err when text is not JSON or does not fit the
type.

A record is read from an object: each member of the object fills the field it names. A field the
object leaves out takes its default, and a field with no default must be there. A member that names
no field is skipped, or is an Err when rejectUnknown is true.

Nothing is converted to make the text fit: "80" is not an int, and null fits only a type that allows
it, such as int \| null. An integer type takes a number written with no fraction and no exponent,
and keeps every digit.

A union is read by the kind of the JSON value: int \| string reads a number as the int and a string
as the string. In a union of two or more records the text names the record: \{"Circle": \{"radius":
1\}\} is a Circle, and "Empty" is a record with no fields. That is the form
[`Json.encode`](https://ant-lang.org/docs/lib/Json/encode.md) writes.

When the text does not fit, the Err names the path of the value, what the type wants, what the text
has, and the line and column, as in "$.servers\[0\].port: want int, got 80.5 at line 1, column 23".

Json.decode panics, whatever the text, on a type with no JSON form: Bytes, Html, void, a function
type, an anonymous record type, a sync or Reflect type, a map keyed by anything but a string, and a
union in which two members read one kind of JSON value, such as UserId \| string.

## Details

- `null` is a value, not a missing member: `port: int = 8080` refuses `"port": null`.
- The whole text must be JSON, whatever the type: a member no field reads is checked all the same,
  and an object that repeats a name is an `Err`.

## Basic examples

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

Json.decode(`{"host": "a.example"}`, type(Server))       // Ok{ value: Server{ host: "a.example", port: 8080 } }
Json.decode(`[1, 2, 3]`, type(Array[int]))               // Ok{ value: [1, 2, 3] }
Json.decode(`{"host": "a", "port": "80"}`, type(Server)) // Err{ error: Error{ message: "$.port: want int, got \"80\" at line 1, column 23", kind: null } }
```

## Scope

Scalars read as their type. A float type takes any number, an integer type only one written as an
integer, every digit kept:

```ant
Json.decode("true", type(bool))            // Ok{ value: true }
Json.decode("2", type(float64))            // Ok{ value: 2.0 }
Json.decode("9007199254740993", type(int)) // Ok{ value: 9007199254740993 }
Json.decode("255", type(byte))             // Ok{ value: 255 }
Json.decode("2.5", type(int))              // Err{ error: Error{ message: "$: want int, got 2.5 at line 1, column 1", kind: null } }
Json.decode("256", type(byte))             // Err{ error: Error{ message: "$: want byte, got 256 at line 1, column 1", kind: null } }
Json.decode(`"caf\u00e9"`, type(string))   // Ok{ value: "café" }
Json.decode("80", type(string))            // Err{ error: Error{ message: "$: want string, got 80 at line 1, column 1", kind: null } }
```

A number too large for a float type is an `Err`, not an infinity:

```ant
Json.decode("1e400", type(float64)) // Err{ error: Error{ message: "$: want float64, got 1e400 at line 1, column 1", kind: null } }
```

A named primitive reads as its base and gets its tag, a map key included:

```ant
type UserId = string
type Score = int

Json.decode(`{"u-1": 10, "u-2": 7}`, type(Map[UserId, Score])) // Ok{ value: Map{ UserId("u-1"): Score(10), UserId("u-2"): Score(7) } }
```

A set drops members that repeat:

```ant
Json.decode(`["go", "ant", "go"]`, type(Set[string])) // Ok{ value: Set.of(["go", "ant"]) }
```

Time values and patterns read from their strings. A duration takes both spellings:

```ant
Json.decode(`"2026-11-28T09:00:00Z"`, type(Time.Instant))  // Ok{ value: 2026-11-28T09:00:00Z }
Json.decode(`["PT30S", "1m"]`, type(Array[Time.Duration])) // Ok{ value: [PT30S, PT1M] }
Json.decode(`"/^a+$/i"`, type(Regex.Pattern))              // Ok{ value: /^a+$/i }
Json.decode(`"next week"`, type(Time.PlainDate))           // Err{ error: Error{ message: "$: want Time.PlainDate, got \"next week\" at line 1, column 1", kind: null } }
```

Records build as a literal would: defaults fill what the object leaves out, and every field without
one must be there:

```ant
type Server = { host: string, port: int = 8080, tags: Array[string] = [] }

Json.decode(`{"host": "a", "tags": ["eu"]}`, type(Server)) // Ok{ value: Server{ host: "a", port: 8080, tags: ["eu"] } }
Json.decode(`{"port": 1}`, type(Server))                   // Err{ error: Error{ message: "$: missing field host at line 1, column 1", kind: null } }
Json.decode(`{"host": "a", "port": null}`, type(Server))   // Err{ error: Error{ message: "$.port: want int, got null at line 1, column 23", kind: null } }
```

A field that may be `null` and may be left out says both:

```ant
type User = { login: string, nick: string | null = null }

Json.decode(`{"login": "ann"}`, type(User))              // Ok{ value: User{ login: "ann", nick: null } }
Json.decode(`{"login": "ann", "nick": "A"}`, type(User)) // Ok{ value: User{ login: "ann", nick: "A" } }
```

A keyword or a name with an underscore is a field name like any other:

```ant
type Event = { type: string, created_at: Time.Instant }

Json.decode(`{"type": "push", "created_at": "2026-11-28T09:00:00Z"}`, type(Event)) // Ok{ value: Event{ type: "push", created_at: 2026-11-28T09:00:00Z } }
```

A union with one member per kind of JSON value reads by kind:

```ant
Json.decode(`[1, null, 3]`, type(Array[int | null]))                  // Ok{ value: [1, null, 3] }
Json.decode(`["a", ["b", "c"]]`, type(Array[string | Array[string]])) // Ok{ value: ["a", ["b", "c"]] }
```

A union of records reads each by its name. A record with no fields is its name alone:

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

Json.decode(`[{"Circle": {"radius": 1}}, "Empty"]`, type(Array[Shape])) // Ok{ value: [Circle{ radius: 1.0 }, Empty{}] }
Json.decode(`{"Square": {"side": "2"}}`, type(Shape))                   // Err{ error: Error{ message: "$.Square.side: want float64, got \"2\" at line 1, column 21", kind: null } }
```

The name alone also reads a member whose fields all have defaults, and the object form reads a
member with no fields:

```ant
type Retry = { times: int = 3 }
type Stop = {}
type Step = Retry | Stop

Json.decode(`"Retry"`, type(Step))      // Ok{ value: Retry{ times: 3 } }
Json.decode(`{"Stop": {}}`, type(Step)) // Ok{ value: Stop{} }
```

An enumeration is a union of records with no fields, so it reads from its names:

```ant
type Debug = {}
type Info = {}
type Level = Debug | Info

Json.decode(`"Debug"`, type(Level)) // Ok{ value: Debug{} }
```

At `Json.Value` it reads any JSON, as [Json.parse](https://ant-lang.org/docs/lib/Json/parse.md) does:

```ant
Json.decode(`{"a": [1, true]}`, type(Json.Value)) // Ok{ value: Map{ "a": [1.0, true] } }
```

Text that is not JSON is an `Err` whatever the type. The message says what was expected and where:

```ant
type Server = { host: string }

Json.decode(`[1, 2,]`, type(Array[int]))                  // Err{ error: Error{ message: "expected a value, found ']' at line 1, column 7", kind: null } }
Json.decode(`{"host": "a", "extra": [1, }`, type(Server)) // Err{ error: Error{ message: "expected a value, found '}' at line 1, column 28", kind: null } }
Json.decode(`{"host": "a"`, type(Server))                 // Err{ error: Error{ message: "unexpected end of JSON input", kind: null } }
Json.decode(`{"host": "a"} {"host": "b"}`, type(Server))  // Err{ error: Error{ message: "unexpected text after the JSON value", kind: null } }
```

In a pipe, the text is the first argument:

```ant
`[1, 2]` | Json.decode(type(Array[int])) | Result.unwrapOr([]) // [1, 2]
```

## Named arguments

`rejectUnknown: true` makes a member that names no field an `Err`, in every record the call reads:

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

Json.decode(`{"host": "a", "prot": 9000}`, type(Server))                      // Ok{ value: Server{ host: "a", port: 8080 } }
Json.decode(`{"host": "a", "prot": 9000}`, type(Server), rejectUnknown: true) // Err{ error: Error{ message: "$.prot: unknown field of Server at line 1, column 15", kind: null } }
```

It bears on records only. A map takes any name:

```ant
Json.decode(`{"x": 1}`, type(Map[string, int]), rejectUnknown: true) // Ok{ value: Map{ "x": 1 } }
```

## Applications

Load a config file a person edits, and say which file a fault is in:

```ant
type Server = { host: string, port: int = 8080 }
type Config = { name: string, servers: Array[Server] }

func loadConfig(path: string): Result[Config, Error] {
  let text = try File.read(path)
  Json.decode(text, type(Config), rejectUnknown: true) | Result.wrapErr(path)
}

println(loadConfig("app.json"))
println(loadConfig("typo.json"))
```

```text
Ok{ value: Config{ name: "prod", servers: [Server{ host: "a.example", port: 8080 }, Server{ host: "b.example", port: 9000 }] } }
Err{ error: Error{ message: "typo.json: $.servers[0].prot: unknown field of Server at line 1, column 52", kind: null } }
```

Decode a list of any type, passing the type along from a generic function:

```ant
type User = { id: int, login: string }

func decodeList[T](body: string, t: Reflect.Type[T]): Result[Array[T], Error] {
  Json.decode(body, Reflect.arrayOf(t))
}

println(decodeList(`[{"id": 1, "login": "ann"}]`, type(User)))
```

```text
Ok{ value: [User{ id: 1, login: "ann" }] }
```

Read a message whose shape depends on one of its members. Decode the member that decides first, then
the whole text at the type it names:

```ant
type Head = { method: string }
type Call[P] = { id: int | null = null, method: string, params: P }
type Rename = { path: string, to: string }

func describe(line: string): Result[string, Error] {
  let head = try Json.decode(line, type(Head))
  if head.method != "rename" {
    return Result.ok("skip ${head.method}")
  }
  let call = try Json.decode(line, type(Call[Rename]))
  Result.ok("rename ${call.params.path} to ${call.params.to}")
}

println(describe(`{"method": "rename", "params": {"path": "a", "to": "b"}}`))
println(describe(`{"method": "ping", "params": {}}`))
```

```text
Ok{ value: "rename a to b" }
Ok{ value: "skip ping" }
```

When each element of an array has a type of its own, keep the part that varies as a
[Json.Raw](https://ant-lang.org/docs/lib/Json/types/Raw.md) and decode it once its type is known:

```ant
type Event = { type: string, data: Json.Raw }
type Counter = { value: int }
type Ratio = { value: float64 }

let body = `[{"type": "counter", "data": {"value": 9007199254740993}}, {"type": "ratio", "data": {"value": 0.5}}]`
for event in try Json.decode(body, type(Array[Event])) {
  let data = string(event.data)
  if event.type == "counter" {
    println(try Json.decode(data, type(Counter)))
  } else {
    println(try Json.decode(data, type(Ratio)))
  }
}
```

```text
Counter{ value: 9007199254740993 }
Ratio{ value: 0.5 }
```

## Properties and relations

[Json.encode](https://ant-lang.org/docs/lib/Json/encode.md) writes text that `Json.decode` reads back at the same type:

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

let shapes: Array[Shape] = [Circle{ radius: 2.0 }, Empty{}]
let t = type(Array[Shape])
assert(Json.decode(Json.encode(t, shapes), t).unwrap() == shapes)
```

[Json.parse](https://ant-lang.org/docs/lib/Json/parse.md) is `Json.decode` at `Json.Value`:

```ant
let text = `{"a": [1, null]}`
assert(Json.parse(text) == Json.decode(text, type(Json.Value)))
```

## Possible issues

[Json.stringify](https://ant-lang.org/docs/lib/Json/stringify.md) writes a record without its name, so a union of records written with
it does not read back. Write with [Json.encode](https://ant-lang.org/docs/lib/Json/encode.md):

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

let shape: Shape = Empty{}
Json.decode(Json.stringify(shape), type(Shape))           // Err{ error: Error{ message: "$: want Shape, got an empty object at line 1, column 1", kind: null } }
Json.decode(Json.encode(type(Shape), shape), type(Shape)) // Ok{ value: Empty{} }
```

A number written with a fraction does not fit an integer type, even when it is whole. Declare the
field a `float64` when the writer spells integers that way:

```ant
Json.decode("5.0", type(int))     // Err{ error: Error{ message: "$: want int, got 5.0 at line 1, column 1", kind: null } }
Json.decode("5.0", type(float64)) // Ok{ value: 5.0 }
```

A field that may be `null` must still be there unless it has a default:

```ant
type User = { login: string, nick: string | null }

Json.decode(`{"login": "ann"}`, type(User)) // Err{ error: Error{ message: "$: missing field nick at line 1, column 1", kind: null } }
```

Give it a default, as in `nick: string | null = null` under [Scope](https://ant-lang.org/docs/lib/Json/decode.md#scope), when it may be left
out.

A record alone with `null` reads bare. A second record in the union makes every record read by name:

```ant
type Circle = { radius: float64 }
type Rect = { width: float64, height: float64 }
type Slot = { a: Circle | null }
type Slot2 = { a: Circle | Rect | null }

Json.decode(`{"a": {"radius": 1}}`, type(Slot))              // Ok{ value: Slot{ a: Circle{ radius: 1.0 } } }
Json.decode(`{"a": {"radius": 1}}`, type(Slot2))             // Err{ error: Error{ message: "$.a: Circle | Rect | null has no member named \"radius\" at line 1, column 8", kind: null } }
Json.decode(`{"a": {"Circle": {"radius": 1}}}`, type(Slot2)) // Ok{ value: Slot2{ a: Circle{ radius: 1.0 } } }
```

An object that repeats a name is an `Err`, even where the type would skip the member, since two
readers could take different values from it:

```ant
type Server = { host: string }

Json.decode(`{"host": "a", "id": 1, "id": 2}`, type(Server)) // Err{ error: Error{ message: "duplicate name \"id\" at line 1, column 24", kind: null } }
```

A name must match exactly, case included. A document that spells an enumeration in lower case reads
into a `string`:

```ant
type Debug = {}
type Info = {}

Json.decode(`"info"`, type(Debug | Info)) // Err{ error: Error{ message: "$: Debug | Info has no member named \"info\" at line 1, column 1", kind: null } }
Json.decode(`"info"`, type(string))       // Ok{ value: "info" }
```

A union in which two members read one kind of JSON value has no JSON form, since the text cannot
tell them apart. The call panics whatever the text:

```ant
type UserId = string

Json.decode(`"u-1"`, type(UserId | string)) // panic: Json.decode: UserId | string: UserId and string are both read from a JSON string
Json.decode("1", type(int | float64))       // panic: Json.decode: int | float64: int and float64 are both read from a JSON number
```

So does a type that JSON cannot hold, wherever it is:

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

Json.decode(`{"name": "a"}`, type(Upload)) // panic: Json.decode: Upload.data: Bytes has no JSON form
```

A map keyed by anything but a string has no JSON form, since a JSON name is a string. Key it by
`string` and convert:

```ant
Json.decode(`{"1": "a"}`, type(Map[int, string]))    // panic: Json.decode: Map[int, string] has no JSON form: a JSON name is a string, and int is not
Json.decode(`{"1": "a"}`, type(Map[string, string])) // Ok{ value: Map{ "1": "a" } }
```

An anonymous record type has no JSON form. Declare a named one:

```ant
Json.decode(`{"x": 1}`, type({ x: int })) // panic: Json.decode: { x: int } has no JSON form: an anonymous record type has none
```

## See also

[Json.encode](https://ant-lang.org/docs/lib/Json/encode.md) · [Json.parse](https://ant-lang.org/docs/lib/Json/parse.md) · [Json.Raw](https://ant-lang.org/docs/lib/Json/types/Raw.md) ·
[Json.Value](https://ant-lang.org/docs/lib/Json/types/Value.md) · [type](https://ant-lang.org/docs/language/keywords/type.md) ·
[Reflect](https://ant-lang.org/docs/lib/Reflect/index.md) · [Field defaults](https://ant-lang.org/docs/guide/records.md#field-defaults)
