Skip to content

Instantly share code, notes, and snippets.

@manjufy
Forked from poteto/flatten_nested_json.ex
Created April 8, 2017 11:53
Show Gist options
  • Save manjufy/0a80d882f803e5174cd53a2d317533a6 to your computer and use it in GitHub Desktop.
Save manjufy/0a80d882f803e5174cd53a2d317533a6 to your computer and use it in GitHub Desktop.
Flatten deeply nested Map in Elixir
defmodule Json do
def flatten(%{} = json) do
json
|> Map.to_list()
|> to_flat_map(%{})
end
def flatten(%{} = json) when json == %{}, do: %{}
defp to_flat_map([{_k, %{} = v} | t], acc), do: to_flat_map(Map.to_list(v), to_flat_map(t, acc))
defp to_flat_map([{k, v} | t], acc), do: to_flat_map(t, Map.put_new(acc, k, v))
defp to_flat_map([], acc), do: acc
end
%{id: "1", foo: %{bar: %{qux: "hello world"}, baz: 123}}
|> Json.flatten()
|> IO.inspect()
# %{baz: 123, id: "1", qux: "hello world"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment