Lavash.JSON (Lavash v0.4.0-rc.1)

Copy Markdown View Source

JSON encoding utilities for Lavash optimistic state.

Handles encoding of Elixir-specific types that Jason doesn't support natively:

  • Tuples are encoded as arrays (e.g., {:edit, "uuid"}["edit", "uuid"])
  • Atoms are encoded as strings (already supported by Jason)
  • All other types pass through to Jason

This allows idiomatic Elixir tagged unions like:

nil | :create | {:edit, id}

To be serialized for JavaScript as:

null | "create" | ["edit", "uuid"]

Summary

Functions

Decodes JSON and converts arrays back to tuples where appropriate.

Encodes a value to JSON, converting tuples to arrays.

Prepares a value for JSON encoding by converting tuples to lists recursively.

Restores Elixir types from JSON-decoded values.

Functions

decode!(json)

Decodes JSON and converts arrays back to tuples where appropriate.

Arrays that look like tagged tuples (first element is a string that looks like an atom) are converted back to tuples.

Examples

iex> Lavash.JSON.decode!(""create"")
:create

iex> Lavash.JSON.decode!("["edit","uuid-123"]")
{:edit, "uuid-123"}

encode!(value)

Encodes a value to JSON, converting tuples to arrays.

Examples

iex> Lavash.JSON.encode!(:create)
""create""

iex> Lavash.JSON.encode!({:edit, "uuid-123"})
"["edit","uuid-123"]"

iex> Lavash.JSON.encode!(nil)
"null"

prepare_for_json(value)

Prepares a value for JSON encoding by converting tuples to lists recursively.

restore_from_json(value)

Restores Elixir types from JSON-decoded values.

  • Strings that look like atoms (lowercase, underscores) become atoms
  • Arrays that look like tagged tuples become tuples