Is it possible to render JSON objects directly inside controller function without the use of view templates?

If so, how? Thank you.

Use the json function instead of the render function. :slight_smile:

12 Likes

@OvermindDL1

I have tried this:

  def pretty_json(conn, data) do
    conn
    |> Plug.Conn.put_resp_header("content-type", "application/json; charset=utf-8")
    |> Plug.Conn.send_resp(200, Poison.encode!(data, pretty: true))
  end

  def show(conn, %{"id" => id}, user) when id == "filter_objects" do
    users = User |> Repo.all
    IO.inspect users
    pretty_json(conn, users)
  end

But I am getting this error message:

(Poison.EncodeError) unable to encode value: {:users, [%Rental.Users.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">,

That is because your structure is not a valid JSON document. Specifically it looks like two problems:

  1. You are using a tuple, tuple’s don’t exist in JSON, make it a list instead.
  2. If you are serializing an ecto record then make sure it derives the poison encoder (see the poison docs). :slight_smile:
3 Likes

Thank you very much. Done :slight_smile:

1 Like