Extract keys using JQ

12 Aug 2016 in TIL

Given the following input data, I needed to extract the key and the value of foo, returning it as a key/value object

json
{
"something": {
"Identifying Key": {
"foo": "a.b.c",
"bar": "First Three"
},
"Another Key": {
"foo": "z.b.d",
"bar": "Second Three, Take Two"
}
}
}

The first thing to do was to step in to the wrapper, something.

bash
cat data.json | jq '.something'

Next, we convert to a structure we can select data from by using to_entries, and unwrap it from it's array by removing the []

bash
cat data.json | jq '.something | to_entries[]'

You can create JSON structures using jq by using braces and providing keys

bash
cat data.json | jq '.something | to_entries[] | {"key": .key, "value": .value.foo}'

Finally, we can zip this up so that it becomes a key/value object like we started with. To do this, we need to wrap our return data with square brackets so that it becomes a list again:

bash
cat data.json | jq '[.something | to_entries[] | {"key": .key, "value": .value.foo}]'

Then we use the from_entries function to remove the key and value keys, zipping them up in to an object. This does the opposite of to_entries

bash
cat data.json | jq '[.something | to_entries[] | {"key": .key, "value": .value.foo}] | from_entries'

This gives us the following output:

json
{
"Identifying Key": "a.b.c",
"Another Key": "z.b.d"
}