Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert maps to struct

Tags:

elixir

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?

like image 494
softshipper Avatar asked Jun 11 '26 02:06

softshipper


2 Answers

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.

like image 88
Patrick Oscity Avatar answered Jun 13 '26 13:06

Patrick Oscity


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

like image 31
sobolevn Avatar answered Jun 13 '26 12:06

sobolevn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!