Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

key

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?

like image 204
k0pernikus Avatar asked Nov 28 '16 15:11

k0pernikus


2 Answers

In your particular case:

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

More robustly:

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

Or if you prefer:

with_entries( .key as $k | .key = (.value|tostring) | .value = $k )

Caveat: all these are potentially lossy.

like image 137
peak Avatar answered Oct 11 '22 09:10

peak


If some keys have equal values then probably you would like to get an array of keys as value:

to_entries
| map( {(.value) : {(.key):null} } )
| reduce .[] as $item ({}; . * $item)
| to_entries
| map({key:.key, value:(.value|keys)})
| from_entries

input:

{
  "key1": "val0",
  "key2": "val1",
  "key3": "val1"
}

output:

{
  "val0": ["key1"],
  "val1": ["key2", "key3"]
}
like image 34
Aleksei Gutikov Avatar answered Oct 11 '22 10:10

Aleksei Gutikov