zatae

zatae

Cannot convert struct to map with Jason @derive

I have a class Company (Echo.Schema)

defmodule MyProject.Company do
  use Ecto.Schema

  ...
  
  @derive {Jason.Encoder, only: [:name]}
  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "companies" do
    field(:name, :string)
    field(:count, :integer, virtual: true)
    has_many(:car, Car, foreign_key: :company_id, references: :id)
    timestamps()
  end

  ...
end

When I try to convert a Company to a Map, it triggers this error:

company |> Map.from_struct()

[error] GenServer #PID<0.820.0> terminating
** (RuntimeError) cannot encode metadata from the :__meta__ field for MyProject.Fleet to JSON. This metadata is used internally by Ecto and should never be exposed externally.

You can either map the schemas to remove the :__meta__ field before encoding to JSON, or explicit list the JSON fields in your schema:

    defmodule MyProject.Fleet do
      # ...

      @derive {Jason.Encoder, only: [:name, :title, ...]}
      schema ... do
...

I don’t understand the error since @derive is set in the model ? Did I forgot to do something ?

I have set Jason as Phoenix JSON parsing lib in config/config.ex :

# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason

Marked As Solved

adamu

adamu

Map.from_struct() is not related to Jason.Encoder. Json.Encoder is a protocol for converting structs to JSON, not maps.

However, both are working for me in this example:

defmodule MyStruct do
  use Ecto.Schema
  @derive {Jason.Encoder, only: [:name]}

  schema "my_struct" do
    field(:name, :string)
    field(:other, :string)
  end
end

Usage:

iex(1)> Jason.encode(%MyStruct{})
{:ok, "{\"name\":null}"}
iex(2)> Map.from_struct(%MyStruct{})
%{
  __meta__: #Ecto.Schema.Metadata<:built, "my_struct">,
  id: nil,
  name: nil,
  other: nil
}

Also Liked

zatae

zatae

I redacted too much code and forgot to tell that this was passed to push_event() right after.

push_event(
  socket,
  "show-company-detail",
  company |> Map.from_struct()
)}

So my guess is that push_event is using Jason to turn the map into JSON. And because I already turned the Company into a Map before, Jason doesn’t clean any fields and __meta__ is still there, triggering this error.

Thanks for pointing out what I was not understanding correctly!

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement