jq is a command-line tool for processing and manipulating JSON data. It provides a simple and powerful way to filter and transform JSON structures in shell scripts.
Installation
To use jq, you need to install it on your system. Here is how you can do it on different platforms:
Mac OS X
brew install jq
Debian-based Linux
sudo apt-get install jq
Red Hat-based Linux
sudo yum install jq
Basic Usage
Once you have jq installed, you can use it to perform various operations on JSON data. Here are some common use cases:
1. Filter JSON data
To filter JSON data based on specific conditions, you can use the select() function. For example, let’s say we have a JSON file called data.json with the following content:
[
{"name": "John", "age": 30},
{"name": "Jane", "age": 25},
{"name": "Mike", "age": 35}
]
We can filter the data to only include persons older than 30:
jq '.[] | select(.age > 30)' data.json
This will output:
{"name":"Mike","age":35}
2. Extract specific fields
You can use jq to extract specific fields from JSON data. For example, let’s say we have the same JSON file as above, and we want to extract only the names of the persons:
jq '.[].name' data.json
This will output:
"John"
"Jane"
"Mike"
3. Combine multiple operations
You can chain multiple operations together using the pipe (** | **) symbol. For example, let’s say we want to filter the JSON data to include only persons older than 30 and then extract their names: |
jq '.[] | select(.age > 30) | .name' data.json
This will output:
"Mike"
Conclusion
jq is a versatile tool for processing and manipulating JSON data in shell scripts. It provides a concise and powerful syntax for filtering and transforming JSON structures. With its easy installation and straightforward usage, jq can greatly enhance your shell scripting workflow.
#tech #shellscripting