将地图转换为结构 [英] Convert maps to struct

查看:82
本文介绍了将地图转换为结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将地图转换为结构,如下所示:

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.

这篇关于将地图转换为结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆