RustyJson.Encode (rustyjson v0.3.9)

Copy Markdown View Source

Low-level encoding functions, compatible with Jason's Encode module.

These functions encode individual Elixir terms to JSON iodata. They are designed for use inside custom RustyJson.Encoder protocol implementations, providing the same API as Jason's Encode module.

Opts

Functions that accept opts use an opaque type matching Jason's Encode.opts(). The opts value is passed to RustyJson.Encoder.encode/2 implementations and should be forwarded to Encode functions as-is.

Examples

defimpl RustyJson.Encoder, for: Money do
  def encode(%{amount: a, currency: c}, opts) do
    RustyJson.Encode.map(%{amount: a, currency: to_string(c)}, opts)
  end
end

Summary

Types

Opaque encoding options.

Functions

Encodes an atom to a JSON string or literal.

Encodes a float to a JSON number.

Encodes an integer to a JSON number.

Encodes a keyword list as an ordered JSON object.

Encodes a list to a JSON array.

Encodes a map to a JSON object.

Builds encoding options from an escape mode.

Encodes a string to a JSON string.

Encodes a struct to JSON.

Encodes any term to JSON iodata.

Types

opts()

@opaque opts()

Opaque encoding options.

Passed to RustyJson.Encoder.encode/2 implementations. Forward to Encode functions as-is.

Functions

atom(atom, arg)

@spec atom(atom(), opts()) :: iodata()

Encodes an atom to a JSON string or literal.

float(float)

@spec float(float()) :: iodata()

Encodes a float to a JSON number.

integer(integer)

@spec integer(integer()) :: iodata()

Encodes an integer to a JSON number.

keyword(list, arg2)

@spec keyword(
  keyword(),
  opts()
) :: iodata()

Encodes a keyword list as an ordered JSON object.

Preserves key insertion order, matching Jason's Encode.keyword/2.

list(list, arg)

@spec list(list(), opts()) :: iodata()

Encodes a list to a JSON array.

map(value, arg)

@spec map(map(), opts()) :: iodata()

Encodes a map to a JSON object.

opts(escape \\ :json)

@spec opts(atom()) :: opts()

Builds encoding options from an escape mode.

Returns an opaque opts value that can be passed to value/2, map/2, string/2, and other encoding functions.

Examples

opts = RustyJson.Encode.opts(:json)
RustyJson.Encode.string("hello", opts)

string(string, arg)

@spec string(String.t(), opts()) :: iodata()

Encodes a string to a JSON string.

struct(value, arg)

@spec struct(
  struct(),
  opts()
) :: iodata()

Encodes a struct to JSON.

value(value, arg)

@spec value(term(), opts()) :: iodata()

Encodes any term to JSON iodata.

Dispatches based on type, matching Jason's Encode.value/2.