Reqord.JSON behaviour (reqord v0.4.0)

View Source

Behavior for JSON encoding and decoding.

This allows users to configure their preferred JSON library for use with Reqord. By default, Reqord uses Jason, but you can configure it to use any JSON library that implements this behavior.

Configuration

In your application config:

config :reqord, :json_library, MyApp.JSONAdapter

Built-in Adapters

Custom Adapters

To create a custom adapter, implement this behavior:

defmodule MyApp.JSONAdapter do
  @behaviour Reqord.JSON

  @impl Reqord.JSON
  def encode!(data) do
    MyJSONLibrary.encode!(data)
  end

  @impl Reqord.JSON
  def decode(binary) do
    case MyJSONLibrary.decode(binary) do
      {:ok, data} -> {:ok, data}
      {:error, reason} -> {:error, %MyJSONLibrary.Error{reason: reason}}
    end
  end

  @impl Reqord.JSON
  def decode!(binary) do
    MyJSONLibrary.decode!(binary)
  end
end

Summary

Callbacks

Decodes JSON binary to Elixir data.

Decodes JSON binary to Elixir data.

Encodes Elixir data to JSON binary.

Functions

Decodes JSON binary to Elixir data using the configured adapter.

Decodes JSON binary to Elixir data using the configured adapter.

Encodes Elixir data to JSON binary using the configured adapter.

Types

decode_error()

@type decode_error() :: Exception.t()

json_binary()

@type json_binary() :: binary()

json_data()

@type json_data() :: term()

Callbacks

decode(json_binary)

@callback decode(json_binary()) :: {:ok, json_data()} | {:error, decode_error()}

Decodes JSON binary to Elixir data.

Returns {:ok, data} on success or {:error, exception} on failure.

decode!(json_binary)

@callback decode!(json_binary()) :: json_data()

Decodes JSON binary to Elixir data.

Raises an exception if decoding fails.

encode!(json_data)

@callback encode!(json_data()) :: json_binary()

Encodes Elixir data to JSON binary.

Raises an exception if encoding fails.

Functions

decode(binary)

@spec decode(json_binary()) :: {:ok, json_data()} | {:error, decode_error()}

Decodes JSON binary to Elixir data using the configured adapter.

Examples

iex> Reqord.JSON.decode(~s({"name":"John"}))
{:ok, %{"name" => "John"}}

iex> Reqord.JSON.decode("invalid json")
{:error, %Jason.DecodeError{...}}

decode!(binary)

@spec decode!(json_binary()) :: json_data()

Decodes JSON binary to Elixir data using the configured adapter.

Raises an exception if decoding fails.

Examples

iex> Reqord.JSON.decode!(~s({"name":"John"}))
%{"name" => "John"}

encode!(data)

@spec encode!(json_data()) :: json_binary()

Encodes Elixir data to JSON binary using the configured adapter.

Examples

iex> Reqord.JSON.encode!(%{name: "John"})
~s({"name":"John"})