Formata.JSON.OrderedObject (formata v0.3.5)

Copy Markdown View Source

A JSON object retaining property order through decoding, edits, and encoding.

A wrapper around a keyword (that supports non-atom keys) allowing for proper protocol implementations.

Implements the Access behaviour and Enumerable protocol with complexity similar to keywords/lists.

Decode with Formata.JSON.decode/2 using objects: :ordered_objects, or construct with new/1. Keys decoded from JSON are always strings. Updating an existing key keeps its position; adding a key through Access prepends it. pop_in/1 removes a key without reordering the others.

Implements Elixir's JSON.Encoder, so ordered objects may also appear inside maps, lists, and structs that derive that protocol. Encoding rejects duplicate keys, including keys that become equal when encoded (such as :name and "name"), with an ErlangError containing {:duplicate_key, key}. Like Elixir's JSON maps, encoding supports string, atom, and numeric keys.

Summary

Functions

Creates a new ordered object from a list of key-value pairs.

Types

key()

@type key() :: String.t() | atom() | number()

t()

@type t() :: %Formata.JSON.OrderedObject{values: [{key(), term()}]}

Functions

new(values)

Creates a new ordered object from a list of key-value pairs.

Example

iex> %{a: 1, c: 3, b: 2}
...> |> Enum.sort()
...> |> Formata.JSON.OrderedObject.new()
...> |> Formata.JSON.encode!()
"{\"a\":1,\"b\":2,\"c\":3}"