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

Converts between MF2 ASTs and the interchange data model of
[TR35 Part 9](https://www.unicode.org/reports/tr35/tr35-messageFormat.html#interchange-data-model),
in its JSON form (the `message.json` schema).

### Purpose

The data model is the logical form of a message, written as plain
data rather than as MF2 syntax. TR35 defines it so that a message
can be passed between implementations and tools without each of
them parsing and printing the syntax: a translation tool can read
and write messages, a linter can inspect them, and a message in
another format, such as ICU MessageFormat 1, can be converted by
building the model. It is not needed to format a message; for that
see `Localize.Message`.

### Reference

The format is not Localize's own. It is defined by:

* [TR35 Part 9, Interchange Data Model](https://www.unicode.org/reports/tr35/tr35-messageFormat.html#interchange-data-model),
  the canonical definition, in TypeScript notation, with a section
  for each of the message, pattern, expression, markup and
  attribute models.

* [`message.json`](https://github.com/unicode-org/message-format-wg/blob/main/spec/data-model/message.json),
  the MessageFormat working group's JSON Schema for the same model,
  which is the form this module reads and writes. It is also
  reproduced in TR35 under
  [`message.json`](https://www.unicode.org/reports/tr35/tr35-messageFormat.html#messagejson).

A message is an object whose `"type"` is `"message"` (one pattern)
or `"select"` (selectors and variants). A pattern is a list of
strings, expressions and markup:

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

### Functions

* `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.

### What the model keeps

The model keeps the meaning of a message, not its spelling: whether
a literal was quoted, whether a message was written in its simple
or its complex form, and the order of an expression's options and
attributes are not kept. A message converted to the model and back
formats as the original does.

`from_json/1` checks the structure of what it is given: every
object's `type`, every name, and that an `.input` declaration's
value names the declared variable. Fields the model does not
define are ignored, as TR35 requires, and `declarations`, `options`
and `attributes` may be left out. It does not check for data model
errors such as a duplicate declaration or a missing fallback
variant; `Localize.Message.Validator.validate/1` does.

# `from_json`

```elixir
@spec from_json(map() | String.t()) :: {:ok, list()} | {:error, Exception.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, or

* `{:error, exception}` if `json` is not JSON, or is not a
  message of the data model. The exception's `:value` is the
  part that was refused.

### Examples

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

    iex> json = %{"type" => "message", "pattern" => [%{"type" => "expression"}]}
    iex> {:error, exception} = Localize.Message.JSON.from_json(json)
    iex> exception.expected
    "an expression with an arg or a function"

# `to_json`

```elixir
@spec to_json(list(), Keyword.t()) :: map() | String.t() | {:error, Exception.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, or

* `{:error, exception}` if `ast` is not an MF2 message AST or
  `options` is not a keyword list.

### Examples

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

    iex> {:ok, ast} = Localize.Message.Parser.parse("{$n :number u:dir=ltr}")
    iex> Localize.Message.JSON.to_json(ast)["pattern"]
    [
      %{
        "type" => "expression",
        "arg" => %{"type" => "variable", "name" => "n"},
        "function" => %{
          "type" => "function",
          "name" => "number",
          "options" => %{"u:dir" => %{"type" => "literal", "value" => "ltr"}}
        }
      }
    ]

---

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