# `LiveSvelte.JSON`
[🔗](https://github.com/woutdp/live_svelte/blob/v0.18.0/lib/live_svelte/json.ex#L1)

JSON encoding using Erlang/OTP 27's native :json module.

This module provides a Jason-compatible interface (`encode!/1`)
that wraps the native Erlang :json module for use with LiveSvelte.

## Features

- Uses Erlang's built-in `:json` module (OTP 27+)
- Automatically converts structs to maps
- Converts all map keys to strings (matching Jason behavior)
- Handles nested data structures
- Converts DateTime/NaiveDateTime/Date/Time to ISO 8601 strings
- Strips Ecto schema metadata (`__meta__` field) automatically

## Usage

This module is the default JSON encoder for LiveSvelte. To use a different
encoder like Jason, configure it in your `config.exs`:

    config :live_svelte, json_library: Jason

## SSR Compatibility Note

When using server-side rendering, the NodeJS worker uses Jason internally
to serialize data to the Node.js process. The `prepare/1` function is used
to convert Elixir terms to JSON-compatible values before passing to NodeJS,
ensuring consistency between SSR and client-side hydration.

# `encode!`

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

Encodes an Elixir term to a JSON string.

Structs are automatically converted to maps before encoding.
Returns a binary string.

## Examples

    iex> LiveSvelte.JSON.encode!(%{foo: "bar"})
    "{"foo":"bar"}"

    iex> LiveSvelte.JSON.encode!([1, 2, 3])
    "[1,2,3]"

# `prepare`

```elixir
@spec prepare(term()) :: term()
```

Prepares an Elixir term for JSON serialization.

This function recursively converts Elixir terms to JSON-compatible values:
- Structs become maps (with `__struct__` key stripped)
- Ecto schemas have `__meta__` field stripped
- DateTime/NaiveDateTime/Date/Time become ISO 8601 strings
- Atoms become strings
- nil becomes :null (for Erlang's :json module)

This is useful for preparing data before passing to external JSON encoders
(like the NodeJS worker which uses Jason internally).

## Examples

    iex> LiveSvelte.JSON.prepare(%DateTime{} = dt)
    "2026-01-31T20:31:10Z"

    iex> LiveSvelte.JSON.prepare(%{notes: [%MyApp.Note{title: "Hello"}]})
    %{"notes" => [%{"title" => "Hello"}]}

---

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