Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Avoid reordering of keys when merging JSON objects with jq

Using jq I want to unflatten a JSON file.

Input

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

Expected output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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
}

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading