Quillon.JSON (Quillon v0.3.0)

Copy Markdown View Source

JSON serialization for Quillon AST nodes.

Converts between Elixir AST tuples and JSON-friendly maps. Uses String.to_existing_atom/1 for security when deserializing.

Custom Node Types

By default, from_json/1 only accepts Quillon's built-in node and mark types. To deserialize documents with custom types, pass a schema or extra types:

# Using a schema (recommended)
schema = Quillon.Schema.merge(Quillon.Schema.default(), my_schema)
Quillon.from_json(json, schema: schema)

# Using extra types
Quillon.from_json(json, extra_types: [:form, :text_input, :step])

# Using extra marks
Quillon.from_json(json, extra_marks: [:custom_mark])

Summary

Functions

Convert a JSON map to an AST node.

Convert a JSON map to an AST node, raising on error.

Convert an AST node to a JSON-friendly map.

Functions

from_json(json, opts \\ [])

@spec from_json(
  map(),
  keyword()
) :: {:ok, tuple()} | {:error, String.t()}

Convert a JSON map to an AST node.

Uses String.to_existing_atom/1 for node types and marks to prevent atom table exhaustion attacks. Only atoms defined in Quillon.Types are valid by default.

Options

  • :schema - A Quillon.Schema to validate types against. Node types are validated against the schema's node keys and marks against the schema's mark keys. Takes precedence over :extra_types/:extra_marks.
  • :extra_types - A list of additional atom node types to accept beyond the built-in types. These atoms must already exist in the atom table.
  • :extra_marks - A list of additional atom mark types to accept beyond the built-in marks. These atoms must already exist in the atom table.

Examples

iex> Quillon.JSON.from_json(%{"type" => "paragraph", "attrs" => %{}, "children" => []})
{:ok, {:paragraph, %{}, []}}

iex> Quillon.JSON.from_json(%{"type" => "unknown", "attrs" => %{}, "children" => []})
{:error, "Unknown node type: unknown"}

from_json!(json, opts \\ [])

@spec from_json!(
  map(),
  keyword()
) :: tuple()

Convert a JSON map to an AST node, raising on error.

Accepts the same options as from_json/2.

Examples

iex> Quillon.JSON.from_json!(%{"type" => "paragraph", "attrs" => %{}, "children" => []})
{:paragraph, %{}, []}

to_json(arg)

@spec to_json(tuple()) :: map()

Convert an AST node to a JSON-friendly map.

Examples

iex> Quillon.JSON.to_json({:paragraph, %{}, [{:text, %{text: "Hi", marks: []}, []}]})
%{
  "type" => "paragraph",
  "attrs" => %{},
  "children" => [
    %{"type" => "text", "attrs" => %{"text" => "Hi", "marks" => []}, "children" => []}
  ]
}

iex> Quillon.JSON.to_json({:text, %{text: "Bold", marks: [:bold, {:link, %{href: "/"}}]}, []})
%{
  "type" => "text",
  "attrs" => %{
    "text" => "Bold",
    "marks" => ["bold", %{"type" => "link", "attrs" => %{"href" => "/"}}]
  },
  "children" => []
}