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…

In JSON (and Elixir) maps order does not matter and you can’t guarantee any ordering when iterating over its members in Elixir or JavaScript or Go or Haskell or …

As NobbZ said, JSON does not maintain ordering of keys. Elixir maps are not ordered as well, so your encoded value may not match the keys order in your code, but this is fine because the spec does not support ordering.

1 Like

@chrismccord Is there any way to workaround this? It’s very important for me to have clean json respones…

That is clean. The JSON Spec itself specified no ordering on objects, just as Javascript specifies no ordering on objects.