将地图转换为结构
问题描述:
我正在尝试将地图转换为结构,如下所示:
I am trying to convert maps to struct as follow:
我有地图:
iex(6)> user
%{"basic_auth" => "Basic Ym1hOmphYnJhMTc=", "firstname" => "foo",
"lastname" => "boo"}
该值应应用于struct:
The value should be applied to struct:
iex(7)> a = struct(UserInfo, user)
%SapOdataService.Auth.UserInfo{basic_auth: nil, firstname: nil, lastname: nil}
如您所见,struct的值为nil,为什么呢?
As you can see, the values of struct is nil, why?
答
到在JustMichael的答案上进行扩展,您可以先使用 String.to_existing_atom / 1
将键转换为原子,然后使用 Kernel.struct / 2
来构建结构:
To expand on JustMichael's answer, you can first convert the keys to atoms, using String.to_existing_atom/1
, then Kernel.struct/2
to build the struct:
user_with_atom_keys = for {key, val} <- user, into: %{} do
{String.to_existing_atom(key), val}
end
user_struct = struct(UserInfo, user_with_atom_keys)
# %UserInfo{basic_auth: "Basic Ym1hOmphYnJhMTc=", firstname: "foo",
lastname: "boo"}
请注意,使用 String.to_existing_atom / 1
来防止VM达到全局Atom限制。
Note that this uses String.to_existing_atom/1
to prevent the VM from reaching the global Atom limit.