Search documentation of Localize

# Localize.Message.JSON (Localize v0.39.0)

Copy Markdown View Source

Converts between MF2 ASTs and the JSON interchange data model defined in TR35 §8.

The JSON data model enables portable serialization of MF2 messages for tooling interoperability. Two functions are provided:

- `to_json/2` — serialize an MF2 AST to a JSON-compatible map or encoded string.

- `from_json/1` — deserialize a JSON map or string back to an MF2 AST.

## Summary

### Functions

from_json(json)

Converts a JSON interchange data model map (or JSON string) back to an MF2 AST.

to_json(ast, options \\ [])

Converts a parsed MF2 AST to the JSON interchange data model.

## Functions

# from_json(json)

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

Converts a JSON interchange data model map (or JSON string) back to an MF2 AST.

### Arguments

- `json` is a map conforming to the MF2 JSON data model, or a JSON-encoded string.

### Returns

- `{:ok, ast}` where `ast` is the MF2 message AST.

- `{:error, reason}` if the JSON structure is invalid.

### Examples

    iex> json = %{"type" => "message", "declarations" => [], "pattern" => ["Hello!"]}
    iex> Localize.Message.JSON.from_json(json)
    {:ok, [{:complex, [], {:quoted_pattern, [{:text, "Hello!"}]}}]}

# to_json(ast, options \\ [])

    @spec to_json(list(), Keyword.t()) :: map() | String.t()

Converts a parsed MF2 AST to the JSON interchange data model.

### Arguments

- `ast` is a parsed MF2 message AST as returned by `Localize.Message.Parser.parse/1`.

- `options` is a keyword list of options.

### Options

- `:encode` — when `true`, returns a JSON-encoded string instead of a map. The default is `false`.

### Returns

- A map (or string when `:encode` is `true`) representing the message in the MF2 JSON data model.

### Examples

    iex> {:ok, ast} = Localize.Message.Parser.parse("{{Hello, world!}}")
    iex> Localize.Message.JSON.to_json(ast)
    %{"type" => "message", "declarations" => [], "pattern" => ["Hello, world!"]}