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.
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})}
Using keys or keys_unsorted could be another:
{mods: [keys_unsorted[] as $name | {$name, enabled: .[$name]}]}
Output:
{
"mods": [
{
"name": "somename",
"enabled": true
},
{
"name": "someothername",
"enabled": false
}
]
}