<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="229952" data-post-id="229952">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="Sebb" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/Sebb/120/21818_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  Sebb
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>OK, now I understood <code>Ecto.Enum</code> - turns out it does exactly what I want:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule Person do
  use Ecto.Schema

  @primary_key false
  embedded_schema do
    field(:id, :integer)
    field(:name, :string, null: false)
    field(:age, :integer)
    field(:job, Ecto.Enum, values: Job.ids())
    field(:hobbies, {:array, Ecto.Enum}, values: Hobby.ids())
    field(:friends, {:array, :integer})
  end
end

defmodule Hobby do
  @hobbies [:hobby_painting, :hobby_freeclimbing, :hobby_stampcollecting]

  def ids(), do: @hobbies
end
</code></pre>
<pre data-code-wrap="elixir"><code class="lang-elixir">iex(1)&gt; data = %{id: 1, name: "Bob", age: "18", job: "job_programmer", friends: [2, 4711], hobbies: ["hobby_freeclimbing", "hobby_painting"]}
iex(2)&gt; p = Ecto.Changeset.cast(%Person{}, data, Map.keys(data)) |&gt; Ecto.Changeset.apply_changes()
%Person{
  age: 18,
  friends: [2, 4711],
  hobbies: [:hobby_freeclimbing, :hobby_painting],
  id: 1,
  job: :job_programmer,
  name: "Bob"
}</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="229952" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-decode-a-json-into-a-struct-safely/14331/22">Post #21</a>
	                </div>
	            </div>
              <div id="likers-container-229952" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="229952"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #21"></div>
  </section>
</div>
    <div class="postbit" id="229959" data-post-id="229959">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="Sebb" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/Sebb/120/21818_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  Sebb
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="al2o3cr" data-post="17" data-topic="14331">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/al2o3cr/48/3457_2.png" class="avatar"> al2o3cr:</div>
<blockquote>
<pre data-code-wrap="elixir"><code class="lang-elixir">field(:job, Job) :: Job.id_t()
field(:hobbies, {:array, Hobby}) :: [Hobby.id_t()]
</code></pre>
</blockquote>
</aside>
<p>Are you using <code>typed_embedded_schema</code> here?</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="229959" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-decode-a-json-into-a-struct-safely/14331/23">Post #22</a>
	                </div>
	            </div>
              <div id="likers-container-229959" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="229959"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #22"></div>
  </section>
</div>
    <div class="postbit" id="231856" data-post-id="231856">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="IvanR" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/IvanR/120/25095_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  IvanR
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>One alternative valid approach is to do the serialization with <a href="https://hex.pm/packages/nestru" rel="nofollow">Nestru</a> like the following:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule Person do
  defstruct [:id, :name, :age, :job, :hobbies, :friends]

  defimpl Nestru.Decoder do
    def from_map_hint(_value, _context, _map) do
      {:ok, %{hobbies: &amp;safe_to_list_of_atoms(&amp;1), job: &amp;safe_to_atom(&amp;1)}}
    end

    defp safe_to_list_of_atoms(list) do
      atoms =
        Enum.reduce_while(list, [], fn item, acc -&gt;
          case safe_to_atom(item) do
            {:ok, atom} -&gt; {:cont, [atom | acc]}
            {:error, _message} = error -&gt; {:halt, error}
          end
        end)
      
      if match?({:error, _message}, atoms) do
        atoms
      else
        {:ok, Enum.reverse(atoms)}
      end
    end

    defp safe_to_atom(binary) do
      try do
        {:ok, String.to_existing_atom(binary)}
      rescue 
        ArgumentError -&gt; {:error, "No atom exists for the value #{inspect(binary)}."}
      end
    end
  end
end
</code></pre>
<p>So for the data with binaries for existing atoms, it returns the struct like that:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">iex(1)&gt; [:hobby_painting, :hobby_freeclimbing, :hobby_stampcollecting]
iex(2)&gt; :job_programmer

iex(3)&gt; data = %{id: 1, name: "Bob", age: "18", job: "job_programmer", friends: [2, 4711], hobbies: ["hobby_freeclimbing", "hobby_painting"]}
iex(4)&gt; Nestru.from_map(data, Person)
{:ok,
 %Person{
   age: "18",
   friends: [2, 4711],
   hobbies: [:hobby_freeclimbing, :hobby_painting],
   id: 1,
   job: :job_programmer,
   name: "Bob"
 }}
</code></pre>
<p>And for the data with binary having no equivalent atom, it will fail like the following:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">iex(5)&gt; data = %{id: 1, name: "Bob", age: "18", job: "job_programmer", friends: [2, 4711], hobbies: ["hobby_freeclimbing", "hobby_gardening"]}
iex(6)&gt; {:error, error} = Nestru.from_map(data, Person)
{:error,
 %{
   get_in_keys: [#Function&lt;8.5372299/3 in Access.key!/1&gt;],
   message: "No atom exists for the value \"hobby_gardening\".",
   path: [:hobbies]
 }}
</code></pre>
<p>And it’s even possible to get the failed piece of the map like that <img src="https://forum.elixirforum.com/images/emoji/apple/slightly_smiling_face.png?v=15" title=":slightly_smiling_face:" class="emoji" alt=":slightly_smiling_face:" loading="lazy" width="20" height="20">:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">iex(7)&gt; get_in(data, error.get_in_keys)
["hobby_freeclimbing", "hobby_gardening"]
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="231856" data-batch-url="/posts/batch_likers">
                        2
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-decode-a-json-into-a-struct-safely/14331/24">Post #23</a>
	                </div>
	            </div>
              <div id="likers-container-231856" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="231856"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #23"></div>
  </section>
</div>
    <div class="postbit" id="266927" data-post-id="266927">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="agreif" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/agreif/120/28392_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  agreif
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>back to the original question…<br>
my idea:</p>
<ol>
<li>decode to a map with atoms as keys</li>
<li>merge it with a new struct</li>
</ol>
<pre data-code-wrap="elixir"><code class="lang-elixir">  @doc ~S"""                                                                                                                                              
  Decode to Struct.                                                                                                                                       
                                                                                                                                                          
  ## Examples                                                                                                                                             
                                                                                                                                                          
      iex&gt; Test.decode_struct("{\"age\":123,\"name\":\"foo\"}", keys: :atoms)                                                                             
      %User{age: 123, name: "foo"}                                                                                                                        
                                                                                                                                                          
  """
  def decode_struct(json_str, opts \\ %{}) do
    %User{} |&gt; Map.merge(Jason.decode!(json_str, opts))
  end
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="266927" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-decode-a-json-into-a-struct-safely/14331/25">Post #24</a>
	                </div>
	            </div>
              <div id="likers-container-266927" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="266927"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #24"></div>
  </section>
</div>
    <div class="postbit" id="266941" data-post-id="266941">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="simonprev" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/simonprev/120/11757_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  simonprev
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>You could use <code>struct!/2</code> to cast a struct and not allow unknown keys to be added to the struct <img src="https://forum.elixirforum.com/images/emoji/apple/wink.png?v=15" title=":wink:" class="emoji" alt=":wink:" loading="lazy" width="20" height="20"></p>
<p><code>%User{} |&gt; Map.merge(%{unknown: "works"})</code> will yield <code>%User{unknown: "works"}</code></p>
<p>But <code>struct!(User, %{unknown: "works"})</code> will raise a KeyError.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="266941" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-decode-a-json-into-a-struct-safely/14331/26">Post #25</a>
	                </div>
	            </div>
              <div id="likers-container-266941" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="266941"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #25"></div>
  </section>
</div>
    <div class="postbit" id="266943" data-post-id="266943">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="agreif" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/agreif/120/28392_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  agreif
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>thanks!</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="266943" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-decode-a-json-into-a-struct-safely/14331/27">Post #26</a>
	                </div>
	            </div>
              <div id="likers-container-266943" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="266943"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>