# `Localize.Message.JSON`
[🔗](https://github.com/elixir-localize/localize/blob/v0.39.0/lib/localize/message/json.ex#L1)

Converts between MF2 ASTs and the JSON interchange data model
defined in [TR35 §8](https://www.unicode.org/reports/tr35/tr35-messageFormat.html).

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.

# `from_json`

```elixir
@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`

```elixir
@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!"]}

---

*Consult [api-reference.md](api-reference.md) for complete listing*
