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

jq: How do I transform an object containing named booleans to an array of `{"name": "aname", "enabled":itsboolean}`s?

I’ve got some json describing plugin states that reads like

{
  "mods": [
    {
        "name": "somename",
        "enabled": true
    },
    {
        "name": "someothername",
        "enabled": false
    }
  ]
}

and I’m attempting to strip the boilerplate out of it for presentation and human editing, then re-insert the boilerplate afterwards. I’ve got the humanizing transform, that’s pleasingly compact and sensible:

jq '[ .mods[]|{(.name): .enabled} ] | add' mod-list.json

{
  "somename": true,
  "someothername": false
}

but I’m stuck on going the other way: I’m looking to transform the output above back to its input.

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

I looked at keys_unsorted,.[] but I don’t see how to splice the sequences together and the manual has worrying comments about the keys being "roughly in insertion order", leaving me to longing for some more explicit guarantee that the keys and values sequences from that construct will at least be in the same order if not the original one.

I also tried foreach and reduce, and they’re tantalizingly close but (a) they gangbang the keys into an array, and (b) I don’t see how to get the corresponding values:

jq 'foreach keys as $key ({};{name:$key, enabled:false}'

So that’s where I’m stuck.

>Solution :

Using to_entries could be one way:

{mods: to_entries | map({name: .key, enabled: .value})}

Demo

Using keys or keys_unsorted could be another:

{mods: [keys_unsorted[] as $name | {$name, enabled: .[$name]}]}

Demo

Output:

{
  "mods": [
    {
      "name": "somename",
      "enabled": true
    },
    {
      "name": "someothername",
      "enabled": false
    }
  ]
}
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