elixirphoenix-frameworkelixir-poison

Strange format of json response


I have a Phoenix app which is basically API. I have the following view:

defmodule TattooBackend.Web.API.V1.AccountView do
  use TattooBackend.Web, :view

  alias TattooBackend.Repo

  def render("my_account.json", %{account: account}) do
    account = account |> Repo.preload(:studio)
    studio  = account.studio

    %{
      id: account.id,
      email: account.email,
      studio: %{
        id: account.studio.id,
        name: account.studio.name
      }
    }
  end
end

When I fire this endpoint in Postman it returns response in following format:

{
    "studio": {
        "name": "asdasdsadsa123123",
        "id": 4
    },
    "id": 1,
    "email": "chujbasd@o2.pl"
}

Why the "id" and "email" are last? They should be first...


Solution

  • You are not guaranteed a return order and really, that's okay. If the order of those values matters then your consumer should probably handle ordering them in the way that it expects so that it's done correctly every time.

    Key-value pairs in a map do not follow any order

    source: https://hexdocs.pm/elixir/Map.html