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"

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

mrzool 2017-12-03

Thanks a lot for this, Michael.

Gordon McCreight 2017-12-27

Thanks for taking the time to write this up, Michael. It mapped very closely to my problem, and helped me resolve it.

kjhkjhkhlkjhkjh 2018-04-04

exactly what I want

Thank you.

emenezes 2018-07-20

very hand and clear. Congratulations.

Bao Tran 2018-09-20

Thank you!

Leave a comment?

Leave a Reply