k0pernikus k0pernikus - 10 days ago 6
JSON Question

How to swap key and value of an object using jq?

Using jq I would like to inverse a json object so that the property becomes the value and the value becomes the key.

Source:

{
"123": "Foobar"
"567": "Poit"
}


Goal:

{
"Foobar": "123"
"Poit": "567"
}


How can I achieve that?

Answer

In your particular case:

to_entries | map( {(.value) : .key } ) | add

More robustly:

to_entries | map( {(.value|tostring) : .key } ) | add