Encoding ordering of Poison.encode

Hi there Elixir fellows :slight_smile:

As I’m playing around with Phoenix and REST API creation I stumbled about an issue with Poison and its way to encode my data into JSON.
I always like to have my JSON data in a particular order in fact in the specific order I declared it in whatever language I use.
Example:

Given the map:
%{error: "my_error_code", reason: "Error description"}

I would like the resulting JSON output to be:
{\"error\":\"my_error_code\",\"reason\":\"Error description\"}

Unfortunately what Poison gives me is:
{\"reason\":\"Error description\",\"error\":\"my_error_code\"}

At first I thought I could just reverse the keys in the map because Poison just encoded my keys in reverse order (same happens with different examples) but that didn’t help.
I know that a computer doesn’t care about the ordering, I just want it for better human readability.
Does anyone of you know what the reason for this behaviour is and how I can get the result I expect/want?

1 Like

Elixir maps are not ordered, when enumerated the keys can appear in any order (the order is stable, but the important thing is that there’s no guarantee of that). Poison would need to sort before encoding and it seems like that’s an unnecessary overhead.
You could take a look at some of the erlang json libraries that support encoding keywords - keywords are always ordered, so there’s a chance it would give what you want. But ultimately JSON objects are specified as order independent, so I would assume most JSON libraries wound’t give any guarantees about the order.

5 Likes

Thank you for your answer.
I didn’t know that map’s keys aren’t guaranteed to be ordered or I just forgot about it.
I’ll have a look at your suggestion and see if that suits my needs :slight_smile:

Edit: I tried mochijson2 and it works just fine.
After further digging around I found the JSON package on hex.pm that also accepts Keywords so I think I’ll stick with that for now.