Linux jq command
jq is a lightweight yet powerful command-line JSON processor. It lets you parse, filter, transform, and format JSON data efficiently, making it especially suitable for handling JSON data in shell scripts.
Main features of jq
- Streaming processing: Can handle JSON data of any size
- Rich set of operators: Provides a variety of operators for processing JSON data structures
- Formatted output: Can pretty-print JSON output for better readability
- Cross-platform: Runs on Linux, macOS, and Windows (via WSL)
Installing jq
On most Linux distributions, jq can be easily installed with a package manager:
Example
Ubuntu/Debian
sudo
apt-get install
jq
CentOS/RHEL
sudo
yum install
jq
Fedora
sudo
dnf
install
jq
macOS (using Homebrew)
brew
install
jq
After installation, you can verify it was successful with the following command:
jq --version
Basic Syntax
The basic command format of jq is as follows:
jq [options] [file...]
Commonly used options
| Option | Description |
|---|---|
-c |
Compact output (not pretty-printed) |
-r |
Output raw strings (without JSON quotes) |
-s |
Read the entire input stream into an array |
-M |
Disable colored output |
--arg |
Define a variable |
--slurp |
Read multiple JSON objects into an array |
Common operation examples
1. Basic JSON parsing
Suppose we have a file named data.json whose contents are as follows:
Example
{
"name": "John Doe",
"age": 30,
"isActive": true,
"address": {
"street": "123 Main St",
"city": "New York"
},
"hobbies": ["reading", "hiking", "coding"]
}
Get all content (pretty-printed output):
jq '.' data.json
Get a specific field:
Example
jq
'.name'
data.json
Output: "John Doe"
Get a nested field:
Example
jq
'.address.city'
data.json
Output: "New York"
2. Array operations
Get array elements:
Example
jq
'.hobbies[0]'
data.json
Output: "reading"
jq
'.hobbies[1:3]'
data.json
Output: ["hiking", "coding"]
Array length:
Example
jq
'.hobbies | length'
data.json
Output: 3
3. Conditional filtering
Filter elements that meet a condition:
Example
Suppose users.json contains an array of users
jq
'.[] | select(.age > 25)'
users.json
4. Data transformation
Create a new object:
Example
jq
'{fullName: .name, city: .address.city}'
data.json
Output: {"fullName": "John Doe", "city": "New York"}
Math operations:
Example
jq
'.age * 2'
data.json
Output: 60
5. Working with multiple files
jq -s '.[0] + .[1]' file1.json file2.json
Advanced usage
1. Using variables
jq --arg new_city "Boston" '.address.city = $new_city' data.json
2. Handling API responses
curl -s https://api.example.com/users | jq '.[] | {name: .name, email: .email}'
3. Complex data transformation
Example
Convert an array of objects to CSV format
jq
-r
'["Name", "Age"], (.[] | [.name, .age]) | @csv'
users.json
4. Error handling
Example
Use try-catch to handle fields that may not exist
jq
'try .unknown_field catch "default value"'
data.json
Practical Application Scenarios
1. Log analysis
Example
Analyze log files in JSON format
cat
app.log
|
jq
'select(.level == "error") | {time: .timestamp, message: .msg}'
2. Configuration processing
Example
Modify a value in a configuration file
jq
'.config.timeout = 30'
config.json
&
gt; temp.json
&
amp;
&
amp;
mv
temp.json config.json
3. Data statistics
Example
Calculate the average age of users
jq
'[.[].age] | add / length'
users.json
Frequently Asked Questions
1. How to handle large JSON files?
For very large JSON files, you can use streaming:
jq -n 'inputs | select(.value > 100)' hugefile.json
2. How to preserve special characters in JSON?
Use -r with the option, special characters are escaped. If you need to output them as-is, you can:
jq -j '.' file.json
3. How to merge multiple JSON files?
jq -s 'add' file1.json file2.json
Summary
jq is a powerful tool for processing JSON data. Through this article, you should have mastered:
- Basic installation and usage of jq
- Common data querying and filtering operations
- Advanced data transformation and processing techniques
- Usage in real-world application scenarios
To further improve your jq skills, you can:
- Practice handling various complex JSON data structures
- Try integrating jq into your shell scripts
- Consult the official jq manual to learn more advanced features
Remember, mastering jq can significantly improve your efficiency in processing JSON data on the command line!
Linux Command Reference