Quillon.JSON (Quillon v0.1.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.

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(arg1)

@spec from_json(map()) :: {: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.

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)

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

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

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" => []
}