json - Elixir: How to convert a keyword list to a map? -
i have keyword list of ecto changeset errors i'd convert map poison json parser can correctly output list of validation errors in json format.
so list of errors follows:
[:topic_id, "can't blank", :created_by, "can't blank"]
...and i'd map of errors so:
%{topic_id: "can't blank", created_by: "can't blank"}
alternatively, if convert list of strings, use well.
the best way accomplish either of these tasks?
what have there isn't keyword list, list every odd element representing key , every element representing value.
the difference is:
[:topic_id, "can't blank", :created_by, "can't blank"] # list [topic_id: "can't blank", created_by: "can't blank"] # keyword list
a keyword list can turned map using enum.into/2
enum.into([topic_id: "can't blank", created_by: "can't blank"], %{})
since data structure list, can convert using enum.chunk/2 , enum.reduce/3
[:topic_id, "can't blank", :created_by, "can't blank"] |> enum.chunk(2) |> enum.reduce(%{}, fn ([key, val], acc) -> map.put(acc, key, val) end)
you can read more keyword lists @ http://elixir-lang.org/getting-started/maps-and-dicts.html
Comments
Post a Comment