Extract keys using JQ

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

{
  "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.

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 []

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

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

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:

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

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

This gives us the following output:

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

Thoughts on this post

Leave a comment?

Leave a Reply