Search code examples
elixir

Convert maps to struct


I am trying to convert maps to struct as follow:

I have a map:

iex(6)> user                      
%{"basic_auth" => "Basic Ym1hOmphYnJhMTc=", "firstname" => "foo",
  "lastname" => "boo"}

The value should be applied to struct:

iex(7)> a = struct(UserInfo, user)
%SapOdataService.Auth.UserInfo{basic_auth: nil, firstname: nil, lastname: nil}

As you can see, the values of struct is nil, why?


Solution

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

    Note that this uses String.to_existing_atom/1 to prevent the VM from reaching the global Atom limit.