Working with Object Keys using JQ in Shell Scripting

In JQ, working with object keys is an essential part of JSON data manipulation. In this tutorial, we’ll explore some JQ commands that allow us to work with object keys in Linux.

Selecting Keys

Suppose we have a JSON object with the following data:

{
  "name": "John",
  "age": 25,
  "city": "New York"
}

To select a specific key from the object, we can use the dot notation followed by the key name. For example, to select the age key, we can use the following command:

jq '.age' file.json

This will output:

25

To select multiple keys, we can use a comma-separated list of key names. For example, to select the name and city keys, we can use the following command:

jq '.name, .city' file.json

This will output:

"John"
"New York"

Renaming Keys

To rename a key in a JSON object, we can use the .|= operator followed by the new key name. For example, to rename the age key to years, we can use the following command:

jq '.years = .age | del(.age)' file.json

This will output:

{
  "name": "John",
  "city": "New York",
  "years": 25
}

Note that we first assign the value of the age key to a new key years using the .|= operator, and then delete the original age key using the del() function.

Filtering by Keys

To filter a JSON object based on a specific key, we can use the select() function. For example, to select objects where the city key is equal to New York, we can use the following command:

jq 'select(.city == "New York")' file.json

This will output:

{
  "name": "John",
  "age": 25,
  "city": "New York"
}

Note that the select() function returns the entire object that matches the condition inside the parentheses.

Also, see the example code shell-scripting-examples in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author