semmitmondo
How to decode a JSON object into a keyword list while preserving the same key order?
How to decode a JSON object into a, for instance, keyword list while preserving the same key order that the JSON string uses?
Elixir maps lose this information because of the underlaying Erlang map implementation.
Most Liked
aseigo
According to the JSON specification, JSON objects are unordered. So if you get the same ordering, it is entirely coincidental or an implementation detail of the underlying library. But you can not rely on ordering of the entries there since they are, by specification, not ordered.
You may want to considering using a list instead if the ordering is absolutely required.
thiagoramos
By the way I had a problem where I had to get the json ordered.
I found out we can use Jason.decode(json_string, %{objects: :ordered_objects})
LostKobrakai
Why combine the data for the key into a string just to need a regex to separate it again. You can have a key like {count, key} in elixir maps.
albertored
This is exactly what I mean, I wrote this “without thinking” to much, just to see if it can work. Thanks for your suggestion!
michalmuskala
Exactly the objects: :ordered_objects is the way to solve this, no need for hacky solutions. It decodes into a Jason.OrderedObject struct that implements Access and Enumerable and can be used similarly to a keyword list. You can also access the .values field for the actual raw keyword. The ordered object struct also encodes into JSON with the specified order.
And yes, while JSON is explicitly not ordered and relying on order is not conforming, there’s not much you can do usually, when interacting with APIs where the order does matter







