jq is a powerful tool to work with JSON from the command-line. The tool has a lot of functions that makes our live easier. For example we can use the keys and keys_unsorted functions to get the keys from an object. The function keys will return the keys in sorted order while keys_unsorted will return them in the original order from the object. With the same functions we can also get the indices of the elements in an array, but there is no sorting involved, so both functions return the same output.

In the following examples we first use keys and then keys_unsorted to get the keys from an object:

$ jq --null-input '{
    "username": "mrhaki",
    "firstName": "Hubert",
    "lastName": "Klein Ikkink"
} | keys'
[
  "firstName",
  "lastName",
  "username"
]
$ jq --null-input '{
    "username": "mrhaki",
    "firstName": "Hubert",
    "lastName": "Klein Ikkink"
} | keys_unsorted'
[
  "username",
  "firstName",
  "lastName"
]

To get the indices of an array we can use the keys function as well:

$ jq --null-input '[1, 10, 100] | keys'
[
  0,
  1,
  2
]

Written with jq 1.7.

shadow-left