SnakeBridge.Types.Encoder (SnakeBridge v0.7.3)

View Source

Encodes Elixir data structures into JSON-compatible formats for Python interop.

Handles lossless encoding of Elixir types that don't have direct JSON equivalents using tagged representations. Tagged values include a __schema__ marker for the current wire schema version. Atom round-trips depend on the decoder allowlist.

Supported Types

Direct JSON Types

  • nilnull
  • Booleans → true/false
  • Integers → numbers
  • Floats → numbers
  • Strings (UTF-8) → strings
  • Lists → arrays
  • Maps with string keys → objects

Tagged Types

  • Atoms → {"__type__": "atom", "value": "ok"}
  • Tuples → {"__type__": "tuple", "elements": [...]}
  • MapSets → {"__type__": "set", "elements": [...]}
  • Binaries (non-UTF-8) → {"__type__": "bytes", "data": "<base64>"}
  • DateTime → {"__type__": "datetime", "value": "<iso8601>"}
  • Date → {"__type__": "date", "value": "<iso8601>"}
  • Time → {"__type__": "time", "value": "<iso8601>"}
  • Special floats → {"__type__": "special_float", "value": "infinity"|"neg_infinity"|"nan"}
  • Maps with atom keys → converted to string keys

Examples

iex> SnakeBridge.Types.Encoder.encode(%{a: 1, b: 2})
%{"a" => 1, "b" => 2}

iex> SnakeBridge.Types.Encoder.encode({:ok, "result"})
%{
  "__type__" => "tuple",
  "__schema__" => 1,
  "elements" => [%{"__type__" => "atom", "__schema__" => 1, "value" => "ok"}, "result"]
}

iex> SnakeBridge.Types.Encoder.encode(MapSet.new([1, 2, 3]))
%{"__type__" => "set", "__schema__" => 1, "elements" => [1, 2, 3]}

Summary

Functions

Encodes an Elixir value into a JSON-compatible structure.

Functions

encode(atom)

@spec encode(term()) :: term()

Encodes an Elixir value into a JSON-compatible structure.

Examples

iex> encode(42)
42

iex> encode(:ok)
%{"__type__" => "atom", "__schema__" => 1, "value" => "ok"}

iex> encode({1, 2, 3})
%{"__type__" => "tuple", "__schema__" => 1, "elements" => [1, 2, 3]}