Home > Enterprise >  Avoid reordering of keys when merging JSON objects with jq
Avoid reordering of keys when merging JSON objects with jq

Time:11-10

Using jq I want to unflatten a JSON file.

Input

{
  "b": 1,
  "c": 2,
  "a:e": 3,
  "a:d": 4
}

Expected output

{
  "b": 1,
  "c": 2,
  "a": {
    "e": 3,
    "d": 4
  }
}

This code reorders the keys alphabetically. Why is this and how can I keep the insertion order?

jq '. as $obj
    | reduce keys[] as $key ({}; . * setpath($key | split(":"); $obj[$key]))'

Output

{
  "a": {
    "d": 4,
    "e": 3
  },
  "b": 2,
  "c": 1
}

CodePudding user response:

keys sorts the keys, keys_unsorted doesn't.

. as $obj | reduce keys_unsorted[] as $key ({};
  . * setpath($key | split(":"); $obj[$key])
)

However, I would rather use to_entries:

reduce to_entries[] as {$key, $value} ({}; 
  setpath($key / ":"; $value)
)
{
  "b": 1,
  "c": 2,
  "a": {
    "e": 3,
    "d": 4
  }
}

Demo

  • Related