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
:jsonmodule (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: JasonSSR 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.
Summary
Functions
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]"
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"}]}