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

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
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
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement