BASH
Parse and Query JSON Data from the Command Line with jq
Master 'jq' for command-line JSON processing. Extract values, filter arrays, and format API responses or config files directly in your terminal.
#!/bin/bash
# Example JSON data (can also be piped from curl or a file)
JSON_DATA='{
"name": "WebApp",
"version": "1.0.0",
"environments": [
{"id": 1, "name": "development", "active": true},
{"id": 2, "name": "staging", "active": false},
{"id": 3, "name": "production", "active": true}
],
"config": {
"port": 8080,
"debugMode": false
}
}'
echo "$JSON_DATA" | jq .name # Get a specific field
echo "$JSON_DATA" | jq .config.port # Access nested fields
echo "$JSON_DATA" | jq '.environments[] | select(.active == true) | .name' # Filter array and extract field
echo "$JSON_DATA" | jq '.environments | length' # Get array length
echo "$JSON_DATA" | jq '{app: .name, envCount: .environments | length}' # Create a new JSON object
# Example with curl (replace with your API endpoint)
# curl -s https://api.github.com/repos/stedolan/jq/releases/latest | jq .tag_name
How it works: This snippet demonstrates `jq`, a powerful command-line JSON processor. It shows how to extract specific fields, access nested properties, filter arrays based on conditions, calculate array lengths, and even construct new JSON objects from existing data. `jq` is indispensable for quickly parsing API responses or configuration files directly in your scripts.