Get key names from JSON using jq

Fetching the key names from a JSON document using jq is simple!

Get key names of JSON using jq

Given a file named example.json,

1
2
3
4
5
{
    "key": "value1",
    "anotherKey": "value2",
    "oneMoreKey": "value3"
}

extracting the keys in alphabetical order can be completed using:

1
jq 'keys' example.json

Output:

1
2
3
4
5
[
  "anotherKey",
  "key",
  "oneMoreKey"
]

Get key names of JSON unsorted using jq

Taking the previous JSON document example.json, the keys may be returned in order as they appear:

1
jq 'keys_unsorted' example.json

Output:

1
2
3
4
5
[
  "key",
  "anotherKey",
  "oneMoreKey"
]

Get key names of JSON in array of objects using jq

Given a file named example.json,

1
2
3
4
5
6
7
8
[
    {
        "key1": "value1"
    },
    {
        "key2": "value2"
    }
]

extracting the keys from the nested array of objects can be completed using:

1
jq '.[] | keys' example.json

Output:

1
2
3
4
5
6
[
  "key1"
]
[
  "key2"
]

If the list is required without the brackets:

1
jq '.[] | keys[]' example.json

Output:

1
2
"key1"
"key2"

Removing the quotes is also an option:

1
jq -r '.[] | keys[]' example.json

Output:

1
2
key1
key2