# `TypeDB.JSON`
[🔗](https://github.com/NoeticEcho/TypedbEx/blob/v0.11.1/typedb/lib/typedb/json.ex#L1)

JSON codec indirection.

JSON needs no dependency of its own. The codec is resolved, once, in this
order:

  1. the module configured as `config :typedb, :json_codec, MyCodec`
  2. `TypeDB.JSON.Native`, backed by the built-in `JSON` module

In practice the list ends there. This driver requires Elixir 1.18, every
version of which has the built-in `JSON`, so step 2 always matches and
**`TypeDB.JSON.Jason` is only ever reached by configuring it**:

    config :typedb, :json_codec, TypeDB.JSON.Jason

`resolve!/0` still falls back to `Jason` and then to an error below step 2.
Neither can execute while the Elixir floor is 1.18, and both are kept because
they are unreachable owing to that floor rather than to being wrong — deleting
them would turn a future change of floor into a silent change of behaviour.

A codec is any module implementing this behaviour.

## The default is also the faster one

Configuring `Jason` is a choice about dependencies, not about speed. Decoding
the same 4.5 MB `conceptRows` answer, median of seven runs on Elixir 1.20.4
and OTP 29:

| codec | |
| --- | ---: |
| built-in `JSON` | 129 ms |
| `Jason` | 180 ms |

Reach for `Jason` if something else in your application already needs it and
you would rather have one codec than two; know that it costs 40% on a large
answer.

# `decode`

```elixir
@callback decode(binary()) :: {:ok, term()} | {:error, term()}
```

Decodes a JSON binary. Returns `{:error, reason}` on malformed input.

# `encode_to_iodata!`

```elixir
@callback encode_to_iodata!(term()) :: iodata()
```

Encodes a term to JSON iodata. Raises on unencodable input.

# `codec`

```elixir
@spec codec() :: module()
```

Returns the resolved codec module.

The result is memoised in `:persistent_term`. Change `:json_codec` before the
first call, or call `reset/0` afterwards.

# `decode`

```elixir
@spec decode(binary()) :: {:ok, term()} | {:error, term()}
```

Decodes a JSON binary.

# `encode!`

```elixir
@spec encode!(term()) :: binary()
```

Encodes `term` to a JSON binary.

# `encode_to_iodata!`

```elixir
@spec encode_to_iodata!(term()) :: iodata()
```

Encodes `term` to JSON iodata.

# `reset`

```elixir
@spec reset() :: :ok
```

Forgets the memoised codec. Intended for tests.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
