Reqord.JSON behaviour (reqord v0.4.0)
View SourceBehavior 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.JSONAdapterBuilt-in Adapters
Reqord.JSON.Jason- Default adapter using the Jason library
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
Callbacks
@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.
@callback decode!(json_binary()) :: json_data()
Decodes JSON binary to Elixir data.
Raises an exception if decoding fails.
@callback encode!(json_data()) :: json_binary()
Encodes Elixir data to JSON binary.
Raises an exception if encoding fails.
Functions
@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{...}}
@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"}
@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"})