Skip to content

Instantly share code, notes, and snippets.

@joeyates
Last active July 10, 2017 21:29
Show Gist options
  • Save joeyates/6d2f70449bcee8cbda5855c8552a7083 to your computer and use it in GitHub Desktop.
Save joeyates/6d2f70449bcee8cbda5855c8552a7083 to your computer and use it in GitHub Desktop.
JSON Serialization of Elixir 2-ples
defimpl JSX.Encoder, for: Tuple do
def json({__t1, __t2}) when is_list(i1) do
[:start_object, "__t1", __t1, "__t2", JSX.encode!(__t2), :end_object]
end
def json({__t1, __t2}) do
[:start_object, "__t1", __t2, "tuple_list", __t2, :end_object]
end
end
# JSON does not allow tuples.
# We have 2-ples, so we encode them as maps
# with conventional keys: __t1 and __t2
defp tuples_to_maps([]) do
[]
end
defp tuples_to_maps([first | rest]) do
[tuples_to_maps(first)] ++ tuples_to_maps(rest)
end
defp tuples_to_maps(%{} = map) do
Enum.reduce(map, %{}, fn ({k, v}, acc) ->
Map.put(acc, k, tuples_to_maps(v))
end)
end
defp tuples_to_maps({i1, i2}) do
%{"__t1" => i1, "__t2" => tuples_to_maps(i2)}
end
defp tuples_to_maps(e) do
e
end
defp maps_to_tuples([]) do
[]
end
defp maps_to_tuples([first | rest]) do
[maps_to_tuples(first)] ++ maps_to_tuples(rest)
end
defp maps_to_tuples(%{"__t1" => i1, "__t2" => i2}) do
{i1, maps_to_tuples(i2)}
end
defp maps_to_tuples(%{} = map) do
Enum.reduce(map, %{}, fn ({k, v}, acc) ->
Map.put(acc, k, maps_to_tuples(v))
end)
end
defp maps_to_tuples(e) do
e
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment