Skip to content

Instantly share code, notes, and snippets.

@hoangbits
Created April 12, 2022 08:51
Show Gist options
  • Save hoangbits/c334d1d890e1258d566d9968b4090d02 to your computer and use it in GitHub Desktop.
Save hoangbits/c334d1d890e1258d566d9968b4090d02 to your computer and use it in GitHub Desktop.
implicit encode Ecto schema with Jason
# inside an ecto Schema, adding this:
defimpl Jason.Encoder, for: [__MODULE__] do
def encode(struct, opts) do
Enum.reduce(Map.from_struct(struct), %{}, fn
({k, %Ecto.Association.NotLoaded{}}, acc) -> acc
({k, v}, acc) -> Map.reject(acc, fn {k, v} -> k === :__meta__ end) |> Map.put(k, v)
end)
|> Jason.Encode.map(opts)
end
end
# suggestion from: https://elixirforum.com/t/how-to-encode-ecto-schema-with-jason-with-all-fields/17221/2
# Notice: I leave it here for testing only. It might be better to use Phoenix view to EXPLICITLY render json.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment