DarckBlezzer
Trying to create an api json in phoenix, gettin error `protocol Jason.Encoder not implemented for `
Hello everyone,
I’m actually studying elixir and phoenix, I’m testing phoenix
I’m learning how to create a rest API JSON
I’m trying to get users and show it as JSON but when try to use json(conn, users) I get this error
protocol Jason.Encoder not implemented for %Test.Accounts.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, id: 3, email: "test@hotmail.com", encrypted_password: "qowejoqiwjeo", valid: true, password: nil, password_confirmation: nil, created_at: ~N[2023-10-05 20:00:46], updated_at: ~N[2023-10-05 20:00:46]} of type Test.Accounts.User (a struct), Jason.Encoder protocol must always be explicitly implemented.
Here is my controller
defmodule TestWeb.TestController do
use TestWeb, :controller
alias Test.Contexts.Users
def test1(conn, _params) do
users = Users.list_users() |> IO.inspect(label: "testcontroller")
json(conn, users)
end
end
The output of IO.inspect
testcontroller: [
%Test.Accounts.User{
__meta__: #Ecto.Schema.Metadata<:loaded, "users">,
id: 3,
email: "test@hotmail.com",
encrypted_password: "qowejoqiwjeo",
valid: true,
password: nil,
password_confirmation: nil,
created_at: ~N[2023-10-05 20:00:46],
updated_at: ~N[2023-10-05 20:00:46]
}
]
I discover that if I delete some elements from the struct
defmodule TestWeb.TestController do
use TestWeb, :controller
alias Test.Contexts.Users
def test1(conn, _params) do
users = Users.list_users() |> IO.inspect(label: "testcontroller")
# This way
# users = users |> Enum.map(&(Map.delete(&1, :__meta__) |> Map.from_struct()))
# or this way
users = users |> Enum.map(&Map.drop(&1, [:__meta__, :__struct__]))
json(conn, users)
end
end
I got the result in explorer
[{"id":3,"valid":true,"password":null,"email":"test@hotmail.com","password_confirmation":null,"created_at":"2023-10-05T20:00:46","encrypted_password":"123123","updated_at":"2023-10-05T20:00:46"},{"id":4,"valid":false,"password":null,"email":"test@gmail.com","password_confirmation":null,"created_at":"2023-10-05T20:39:23","encrypted_password":"123123123","updated_at":"2023-10-05T20:39:23"}]
My questions are the next
- I don’t know if I’m doing it correctly, but this is the right way?
- I need always to delete
:__meta__and:__struct__and others elements to work correctly? - I discovery that you can create a module to have the bodies format o similar to this:
defmodule TestWeb.TestJSON do
def all(%{users: users}) do
for(user <- users, do: data(user)
end
defp data(%User{} = user) do
%{
id: user.id,
emai: user.email,
valido: user.valid,
creado: user.created_at,
modificado: user.updated_at
}
end
end
# And use in the controller like this...
defmodule TestWeb.TestController do
use TestWeb, :controller
alias Test.Contexts.Users
def test1(conn, _params) do
users = Users.list_users()
render(conn, :all, users: users)
end
end
- Another question, is there a way to render, sending all users like this
render(conn, :all, users)and receive like thisdef all(users) do?
Most Liked
kokolegorille
No need to touch special struct keys… You could always use Map.from_struct
The way to render struct to json is with the @derive attribute
Or in a module that produces your custom json (like in api views…)
2
dimitarvp
Just do:
users = users |> Enum.map(&Map.from_struct/1)
json(conn, users)
Unless you really want a custom encoder – which would likely just skip a few fields? – then that’s a good way to do it.
1
Popular in Questions
The Elixir Typespec docs show the following syntax for keyword lists in typespecs:
# ...
| [key: type] # keyword lists...
New
Hello, I have map which I want to convert it to string like this:
the map:
%{last_name: "tavakkoli", name: "shahryar"}
the string I ne...
New
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set?
Thanks.
New
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
lets say i have a sample like
a = 20; b = 10;
if (a > b) do
{:ok, "a"}
end
if (a < b) do
{:ok, b}
end
if (a == b) do
{:ok, "equa...
New
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)?
Would
mix ecto.rollback -v 200809061...
New
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this
"1000"
What is the ...
New
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
Hi,
I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
Other popular topics
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Phoenix 1.4.0 released
Phoenix 1.4 is out! This release ships with exciting new features, most notably
with HTTP2 support, improved deve...
New
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
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
I have VueJS GUIs with the project generated using Webpack.
I have Elixir modules that will need to be used by the VueJS GUIs.
I forese...
New
Hi folks,
Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
New
Hi everyone,
I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








