Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alphabetical sorting order for keys #152

Open
pulzzejason opened this issue Dec 19, 2017 · 1 comment
Open

Alphabetical sorting order for keys #152

pulzzejason opened this issue Dec 19, 2017 · 1 comment

Comments

@pulzzejason
Copy link

I would like to print out the JSON maps in alphabetical order.

I noticed that the encode function will always return the keys in reverse order. Am I missing something? I'm surprised that an option for alphabetical order hasn't been requested already.

iex(15)> %{"a"=>1,"b"=>2} |> Poison.encode!()                                                                            
"{\"b\":2,\"a\":1}"
iex(16)> %{"b"=>1,"a"=>2} |> Poison.encode!()
"{\"b\":1,\"a\":2}"
iex(23)> %{} |> Map.put("a", 1) |> Map.put("c", 3) |> Map.put("b", 2) |> Poison.encode!(pretty: true) |> IO.puts
{
  "c": 3,
  "b": 2,
  "a": 1
}
@ivan
Copy link
Contributor

ivan commented Dec 19, 2017

Add more keys and you will hit a threshold at which they're no longer in a discernible order; #21 (comment)

I have also needed this, though, when I was writing some tests that embedded JSON inside another document. I used this function to encode:

  @doc """
  Encode a map to JSON with all of the keys in alphabetical order
  (including for objects nested inside this object).
  """
  def encode_object_in_alphanumeric_key_order(obj) when is_map(obj) do
    az_keys = obj |> Map.keys |> Enum.sort
    iodata = [
      "{",
      Enum.map(az_keys, fn k ->
        v = obj[k]
        [Poison.encode!(k), ":", encode_object_in_alphanumeric_key_order(v)]
      end) |> Enum.intersperse(","),
      "}"
    ]
    IO.iodata_to_binary(iodata)
  end
  def encode_object_in_alphanumeric_key_order(obj), do: Poison.encode!(obj)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants