How to convert the structure of an Erlang object to an Elixir Map?

I use couchbeam to contact Elixir's CouchDB.

But lib returns to me the previous representation of the erlang object as {[{"foo", "bar"}]}, not elixir maps, it was connected to lib using jiffy: decode without return_maps, how to convert this object structure to Elixir maps (and vice versa) Versa)?

I found the hacky way jiffy: encode and jiffy: decode it again with return_maps... But should there be another alternative?

Update:

From the Hynek example in erlang, it 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

It seems to do the job.

iex(1)> ToMaps.convert({[{"foo",[{[{"a",1}]},3]},{"bar","baz"}]})

%{"bar" => "baz", "foo" => [%{"a" => 1}, 3]}
+3
source share
2 answers

, :

-module(to_maps).

-export([to_maps/1]).

to_maps({L}) when is_list(L) ->
    maps:from_list([{K, to_maps(V)} || {K, V} <- L]);
to_maps([H|T]) ->
    [to_maps(H) | to_maps(T)];
to_maps(X) -> X.

Edit

:

from_maps(#{} = M) ->
    F = fun(K, V, Acc) -> [{K, from_maps(V)} | Acc] end,
    {maps:fold(F, [], M)};
from_maps([H|T]) ->
    [from_maps(H) | from_maps(T)];
from_maps(X) -> X.

, :

convert({L}) when is_list(L) ->
    maps:from_list([{K, convert(V)} || {K, V} <- L]);
convert(#{} = M) ->
    F = fun(K, V, Acc) -> [{K, convert(V)} | Acc] end,
    {maps:fold(F, [], M)};
convert([H|T]) ->
    [convert(H) | convert(T)];
convert(X) -> X.

:

1> jiffy:decode(<<"{\"foo\":[3, {\"a\":1}], \"bar\":\"baz\"}">>).
{[{<<"foo">>,[3,{[{<<"a">>,1}]}]},{<<"bar">>,<<"baz">>}]}
2> to_maps:to_maps(v(-1)).
#{<<"bar">> => <<"baz">>,<<"foo">> => [3,#{<<"a">> => 1}]}
3> to_maps:from_maps(v(-1)).
{[{<<"foo">>,[3,{[{<<"a">>,1}]}]},{<<"bar">>,<<"baz">>}]}
4> to_maps:convert(v(-1)).
#{<<"bar">> => <<"baz">>,<<"foo">> => [3,#{<<"a">> => 1}]}
5> to_maps:convert(v(-1)).
{[{<<"foo">>,[3,{[{<<"a">>,1}]}]},{<<"bar">>,<<"baz">>}]}
6> to_maps:convert(v(-1)).
#{<<"bar">> => <<"baz">>,<<"foo">> => [3,#{<<"a">> => 1}]}
...
+4

, , - :

iex(1)> Enum.into([{"foo", "bar"}], %{})
%{"foo" => "bar"}
0

Source: https://habr.com/ru/post/1662139/


All Articles