RustyJson.Helpers (rustyjson v0.3.9)

Copy Markdown View Source

Compile-time helpers for JSON encoding, compatible with Jason's Helpers module.

Provides macros that pre-encode JSON object keys at compile time for faster runtime encoding.

Examples

import RustyJson.Helpers

def render(user) do
  json_map(name: user.name, email: user.email)
end

def render_partial(user) do
  json_map_take(user, [:name, :email])
end

Summary

Functions

Encodes a keyword list as a JSON object with keys pre-encoded at compile time.

Encodes selected keys from a map as a JSON object with keys pre-encoded at compile time.

Functions

json_map(kv)

(macro)

Encodes a keyword list as a JSON object with keys pre-encoded at compile time.

Values are encoded at runtime. Returns a %RustyJson.Fragment{}.

Keys must be atoms with ASCII printable characters only (no \, /, ").

Examples

iex> import RustyJson.Helpers
iex> fragment = json_map(name: "Alice", age: 30)
iex> RustyJson.encode!(fragment, protocol: true)
~s({"name":"Alice","age":30})

json_map_take(map, take)

(macro)

Encodes selected keys from a map as a JSON object with keys pre-encoded at compile time.

Takes a map and a compile-time list of atom keys. Values are looked up and encoded at runtime. Returns a %RustyJson.Fragment{}.

Raises ArgumentError at runtime if the map is missing any of the specified keys.

Examples

iex> import RustyJson.Helpers iex> user = %{name: "Alice", age: 30, email: "alice@example.com"} iex> fragment = json_map_take(user, [:name, :age]) iex> RustyJson.encode!(fragment, protocol: true) ~s({"name":"Alice","age":30})