semmitmondo

semmitmondo

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.

Showing Posts 1 to 10

aseigo

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.

OvermindDL1

OvermindDL1

Precisely this. JSON specifies that objects are unordered but array’s are ordered, so if order is important then it should be an array, not an object.

albertored

albertored

I know specification says JSON objects are unordered but sometimes preserving the order can be useful.

Take for instances a situation where you want to read an external JSON file, apply some small changes and write it back preserving the order so to not create large diffs (the file can be under version control).

For instance in python you can do this with this code:

import json
from collections import OrderedDict
json.load(input_json, object_pairs_hook=OrderedDict)

In Elixir I am only able to write JSON objects in a custom order by using Keyword instead of Map but I haven’t find a way of reading a JSON object into a Keyword.

LostKobrakai

LostKobrakai

In jason it seems like objects are actually decoded into a list until the whole object is read and only at that moment the list is converted to a map:

https://github.com/michalmuskala/jason/blob/v1.2.2/lib/decoder.ex#L284

But given jason seems to want to be spec compliant I’m not sure it would accept changing that.

albertored

albertored

Thanks, I am able to use this :jason implementation detail to get what I want.

It is a very far from optimal solution, surely not performant and relies on the order in which keys are decoded by Jason but it seems to work for my needs (it’s more like a script than something that should be done a lot of times per second).

I put it here just for people that may have my same requirements but I wrote it without optimizing it so be kind with your comments :smiley:

defmodule StringKeyword do
  defstruct data: []

  @spec decode!(binary) :: any
  def decode!(string) when is_bitstring(string) do
    Process.put(:key_count, 0)
    
    string
    |> Jason.decode!(
      keys: fn key ->
        count = Process.get(:key_count)
        Process.put(:key_count, count + 1)
        {count, key}
      end
    )
    |> new()
  end

  defp new(conf) when is_map(conf) do
    data =
      conf
      |> Map.to_list()
      |> Enum.sort_by(fn {{idx, _}, _} -> idx end)
      |> Enum.map(fn {{_, k}, v} -> {k, new(v)} end)

    %__MODULE__{data: data}
  end

  defp new(list) when is_list(list), do: Enum.map(list, &new/1)

  defp new(value), do: value
end

defimpl Jason.Encoder, for: StringKeyword do
  def encode(%{data: value}, opts), do: Jason.Encode.keyword(value, opts)
end

defmodule Sorted do
  def run(input, output) do
    input
    |> File.read!()
    |> StringKeyword.decode!()
    |> Jason.encode!(pretty: [indent: "    "])
    |> (&File.write!(output, &1)).()
  end
end

Edited as per @LostKobrakai suggestion

JeyHey

JeyHey

How do you write the loaded json back? Wouldn’t the order of the keys be not deterministic in this step?

albertored

albertored

By using Jason.Encode.keyword/2. This function preserves the order of the Keyword in encoding it.

LostKobrakai

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

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!

thiagoramos

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})

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews