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?
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.
You can try exconstructor. It does exactly what you need.
Here's a small example:
defmodule TestStruct do
defstruct field_one: nil,
field_two: nil,
field_three: nil,
field_four: nil
use ExConstructor
end
TestStruct.new(%{"field_one" => "a", "fieldTwo" => "b", :field_three => "c", :FieldFour => "d"})
# => %TestStruct{field_one: "a", field_two: "b", field_three: "c", field_four: "d"}
Link to the documentation: http://hexdocs.pm/exconstructor/ExConstructor.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With