I am using couchbeam to contact CouchDB from Elixir.
But the lib gives me back old erlang object representation like {[{"foo", "bar"}]}
and not elixir maps, this was due to the lib using jiffy:decode without return_maps
, How do I convert this object structure to Elixir maps (and vice versa)?
I found a hackish way to jiffy:encode and jiffy:decode it again with return_maps
... But there must be another alternative?
Update:
From Hynek's example in erlang, This seems to work:
defmodule ToMaps do
def convert({x}) when is_list(x) do
Map.new(x, fn {k, v} -> {k, convert(v)} end)
end
def convert([head | tail]) do
[convert(head) | convert(tail)]
end
def convert(x) do
x
end
end
Seems to do the job.
iex(1)> ToMaps.convert({[{"foo",[{[{"a",1}]},3]},{"bar","baz"}]})
%{"bar" => "baz", "foo" => [%{"a" => 1}, 3]}
I don't know Elixir but in Erlang:
Edit:
Reverse:
I would not recommend it but It can be even one function:
Usage: