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

Elixir: How to convert a keyword list to a map?

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

我得到如下错误列表:

[:topic_id, "can't be blank", :created_by, "can't be blank"]

...我想得到一张错误图,如下所示:

%{topic_id: "can't be blank", created_by: "can't be blank"}

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

完成其中一项任务的最佳方法是什么?

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

区别是:

[: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

可以使用 Enum.into/2

将关键字列表转换为地图
Enum.into([topic_id: "can't be blank", created_by: "can't be blank"], %{})

因为你的数据结构是一个列表,你可以使用Enum.chunk_every/2 and Enum.reduce/3

转换它
[:topic_id, "can't be blank", :created_by, "can't be blank"]
|> Enum.chunk_every(2)
|> Enum.reduce(%{}, fn ([key, val], acc) -> Map.put(acc, key, val) end)

您可以在 http://elixir-lang.org/getting-started/maps-and-dicts.html

阅读有关关键字列表的更多信息

另一种方法是将 Enum.chunk/2Enum.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)

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

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"}

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

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

它在某些情况下也很有用。

您可以在 http://elixir-lang.org/getting-started/comprehensions.html#results-other-than-lists

阅读有关此用例的更多信息