Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

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

I have a keyword list of Ecto changeset errors I'd like to convert to a map so that the Poison JSON parser can correctly output a list of validation errors in the JSON format.

I get a list of errors as follows:

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

...and I'd like to get a map of errors like so:

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

Alternatively, if I could convert it to a list of strings, I could use that as well.

What is the best way to accomplish either of these tasks?

question from:https://stackoverflow.com/questions/31549555/elixir-how-to-convert-a-keyword-list-to-a-map

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you have there isn't a keyword list, it is just a list with every odd element representing a key and every even element representing a value.

The difference is:

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

A keyword list can be turned into a map using Enum.into/2

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

Since your data structure is a list, you can convert it using 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)

You can read more about Keyword lists at http://elixir-lang.org/getting-started/maps-and-dicts.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...