Home > Back-end >  How to return JSON of an Ecto result in Phoenix
How to return JSON of an Ecto result in Phoenix

Time:10-07

I am new to Phoenix, and using it for a backend, and currently am trying to return the result of Repo.all as JSON to the user.

I have this working in the following way (in user_controller.ex)

def index(conn, _params) do
    result = Repo.all(User)
    users = Enum.map(result
        fn user ->
            Map.take(user, [:id, :firstname, :lastname, :username])
        end)
    conn |> json(users)
end

but this feels like I'm taking unnecessary steps when there may just be a simple function.

Is this the most idiomatic way to send an Ecto result as JSON?

CodePudding user response:

You have multiple ways to do it, depending on what you exactly want, for example :

  • If you want every fields you can use :
User
|> Repo.all()
|> Enum.map(fn user -> 
  user |> Map.from_struct
end)

This will return all User and apply Map.from_struct to every user found.

  • If you want only specific fields, you can use :
from(
    u in User,
    select: map(u, [:id, :email])
) |> Repo.all()

This will return an array of map containing only select fields. (Ecto.Query.API.map)

  • Related