[英]How to convert Erlang object structure to Elixir Map?
I am using couchbeam to contact CouchDB from Elixir. 我正在使用couchbeam从Elixir联系CouchDB。
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)? 但lib给了我回老的erlang对象表示,如{[{"foo", "bar"}]}
而不是elixir地图,这是由于lib使用jiffy:decode而不是return_maps
,如何将此对象结构转换为Elixir地图(反之亦然)?
I found a hackish way to jiffy:encode and jiffy:decode it again with return_maps
... But there must be another alternative? 我发现了jiffy的一种hackish方式:encode和jiffy:用return_maps
再次解码它......但是必须有另一种选择吗?
From Hynek's example in erlang, This seems to work: 从Hynek在erlang中的例子来看,这似乎有效:
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: 我不知道Elixir但是在Erlang:
-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 : 编辑 :
Reverse: 相反:
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.
I would not recommend it but It can be even one function: 我不推荐它,但它甚至可以是一个功能:
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.
Usage: 用法:
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}]}
...
I need to see all of your data structure to say for sure but you can use something like this : 我需要确定您的所有数据结构,但您可以使用以下内容:
iex(1)> Enum.into([{"foo", "bar"}], %{})
%{"foo" => "bar"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.