Elixir:如何将关键字列表转换为地图?

Eri*_*udd 32 json elixir

我有一个Ecto变更集错误的关键字列表我想转换为地图,以便Poison JSON解析器可以正确输出JSON格式的验证错误列表.

所以我得到一个错误列表如下:

[:topic_id, "can't be blank", :created_by, "can't be blank"]
Run Code Online (Sandbox Code Playgroud)

...我想得到一个错误的地图,如下所示:

%{topic_id: "can't be blank", created_by: "can't be blank"}
Run Code Online (Sandbox Code Playgroud)

或者,如果我可以将其转换为字符串列表,我也可以使用它.

完成这两项任务的最佳方法是什么?

Gaz*_*ler 51

你所拥有的不是关键字列表,它只是一个列表,每个奇数元素代表一个键,每个偶数元素代表一个值.

不同之处是:

[:topic_id, "can't be blank", :created_by, "can't be blank"] # List
[topic_id: "can't be blank", created_by: "can't be blank"]   # Keyword List
Run Code Online (Sandbox Code Playgroud)

可以使用Enum.into/2将关键字列表转换为地图

Enum.into([topic_id: "can't be blank", created_by: "can't be blank"], %{})
Run Code Online (Sandbox Code Playgroud)

由于您的数据结构是一个列表,您可以使用Enum.chunk/2Enum.reduce/3进行转换

[:topic_id, "can't be blank", :created_by, "can't be blank"]
|> Enum.chunk(2)
|> Enum.reduce(%{}, fn ([key, val], acc) -> Map.put(acc, key, val) end)
Run Code Online (Sandbox Code Playgroud)

您可以在http://elixir-lang.org/getting-started/maps-and-dicts.html上阅读有关关键字列表的更多信息.

  • 我现在无法尝试,但我觉得你应该能够将最后一个例子减少到`[...] |> Enum.chunk(2)|> Enum.into(%{}) ` (3认同)

Gja*_*don 11

另一种方法是结合Enum.chunk/2使用Enum.into/3.例如:

[:topic_id, "can't be blank", :created_by, "can't be blank"]
|> Enum.chunk(2)
|> Enum.into(%{}, fn [key, val] -> {key, val} end)
Run Code Online (Sandbox Code Playgroud)


Rom*_*nov 6

另一种方法是使用列表理解:

iex> list = [:topic_id, "can't be blank", :created_by, "can't be blank"]
iex> map = for [key, val] <- Enum.chunk(list, 2), into: %{}, do: {key, val}
%{created_by: "can't be blank", topic_id: "can't be blank"}
Run Code Online (Sandbox Code Playgroud)

此外,您可以将列表转换为关键字列表:

iex> klist = for [key, val] <- Enum.chunk(list, 2), do: {key, val}
[topic_id: "can't be blank", created_by: "can't be blank"]
Run Code Online (Sandbox Code Playgroud)

在某些情况下它也可能有用.

您可以在http://elixir-lang.org/getting-started/comprehensions.html#results-other-than-lists上阅读有关此用例的更多信息.