Guide: How to enforce key sort order when JSON encoding a struct (using Jason or JSON)

Here you go:

iex(1)> Mix.install [:jason]
:ok
iex(2)> map = %{a: 10, b: 3, c: 1, d: 100}
%{c: 1, a: 10, b: 3, d: 100}
iex(3)> map |> Enum.sort_by(&elem(&1,1)) |> Jason.OrderedObject.new() |> Jason.encode!(pretty: true) |> IO.puts()
{
  "c": 1,
  "b": 3,
  "a": 10,
  "d": 100
}
4 Likes