how.wtf

Get key names from JSON using jq

· Thomas Taylor

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    "key": "value1",
3    "anotherKey": "value2",
4    "oneMoreKey": "value3"
5}

extracting the keys in alphabetical order can be completed using:

1jq 'keys' example.json

Output:

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

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:

1jq 'keys_unsorted' example.json

Output:

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

Get key names of JSON in array of objects using jq

Given a file named example.json,

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

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

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

Output:

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

If the list is required without the brackets:

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

Output:

1"key1"
2"key2"

Removing the quotes is also an option:

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

Output:

1key1
2key2

#linux  

Reply to this post by email ↪