Search code examples
elixirphoenix-frameworkelixir-poison

Why does phoenix controller returns a json which can't be recognized as JSON


I'm trying to replace old rails application by the new phoenix. I'm sending the ajax request and I'm trying to recognize is as JSON via jQuery automatically. The problem is that rails returns this content:

{"user_id":1,"user_avatar_url":"/avatar.png"}

while my phoenix app returns this:

"{\"id\":1,\"avatar_url\":\"/avatar.png\"}"

so I need to run JSON.parse to recognize this content as json object. What can I do to implement it parsed automatically?

My phoenix code:

# the controller part responsible for rendering
conn
|> put_session(:user_id, user.id)
|> json(Poison.encode!(user))

# poison serializer placed in model
  defimpl Poison.Encoder, for: Harvest.User do
    def encode(user, _options) do
      user
      |> Map.put(:avatar_url, "/avatar.png")
      |> Map.take([:id, :avatar_url])
      |> Poison.encode!([])
    end
  end

Solution

  • You don't need to manually encode a term using Poison.encode! when using Phoenix.Controller.json/2, it handles that for you. Your data is getting double encoded right now.

    Your code should just be:

    conn
    |> put_session(:user_id, user.id)
    |> json(user)