SnakeBridge.Types.Encoder (SnakeBridge v0.7.4)

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>"}
  • SnakeBridge.Bytes{"__type__": "bytes", "data": "<base64>"} (always bytes)
  • 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 string/atom keys → plain objects (keys converted to strings)
  • Maps with non-string keys → {"__type__": "dict", "pairs": [[key, val], ...]}

Unsupported Types

The following types cannot be serialized and will raise SnakeBridge.SerializationError:

  • PIDs, ports, references
  • Custom structs without explicit encoder support

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]}

iex> SnakeBridge.Types.Encoder.encode(%{1 => "one", 2 => "two"})
%{"__type__" => "dict", "__schema__" => 1, "pairs" => [[1, "one"], [2, "two"]]}

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]}

Raises