egze
StableJason - a library for encoding Elixir values to a stable JSON with deterministic sorting for keys
StableJason is a library for encoding Elixir values to a stable JSON with deterministic sorting for keys.
It works similar like OJSON but can output a pretty JSON string, using Jason as the underlying JSON encoder.
The initial use-case for this library is to display a diff between two JSON files. The problem with JSON is that the order of keys is not guaranteed, so a diff between two JSON files can be very noisy. By using StableJason to encode the JSON files, the order of keys is deterministic, so the diff will be much more readable.
It also supports a :sorter option (:asc, :desc, or a function), if you need to override it even further.
Examples
StableJason.encode(%{c: 3, b: 2, a: 1})
{:ok, ~S|{"a":1,"b":2,"c":3}|}
StableJason.encode(%{c: 3, b: 2, a: 1}, sorter: :asc, pretty: true)
{:ok, "{\n \"a\": 1,\n \"b\": 2,\n \"c\": 3\n}"}
StableJason.encode!(%{c: 3, b: 2, a: 1})
"{\"a\":1,\"b\":2,\"c\":3}"
StableJason.encode!(%{c: 3, b: 2, a: 1}, sorter: :asc, pretty: true)
"{\n \"a\": 1,\n \"b\": 2,\n \"c\": 3\n}"
Links
Hex.pm: https://hex.pm/packages/stable_jason
Hexdocs: https://hexdocs.pm/stable_jason/readme.html
GitHub:
Most Liked
LostKobrakai
Jason can already decode to Jason.OrderedObject and encode this again preserving ordering.
egze
Yes, that’s what the library is using, but also sorts (which Jason doesn’t do).
mudasobwa
FWIW, if the shape is known in advance, one might reach out to Estructura.diff/3 to get a difference between two JSON objects.
Popular in Announcing
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








