BASH
Parse and Extract Data from JSON Files with jq
Learn to efficiently parse and extract specific data from JSON files and API responses using the powerful `jq` command-line JSON processor in bash scripts.
#!/bin/bash
# Example JSON data (can also be piped from a file or curl)
JSON_DATA='{
"name": "WebApp",
"version": "1.0.0",
"config": {
"port": 8080,
"debugMode": true
},
"dependencies": [
{"package": "express", "version": "^4.17.1"},
{"package": "react", "version": "^17.0.2"}
]
}'
# Extract a top-level key
APP_NAME=$(echo "$JSON_DATA" | jq -r '.name')
echo "App Name: $APP_NAME"
# Extract a nested key
PORT=$(echo "$JSON_DATA" | jq -r '.config.port')
echo "Port: $PORT"
# Extract an element from an array of objects
FIRST_DEPENDENCY_PACKAGE=$(echo "$JSON_DATA" | jq -r '.dependencies[0].package')
echo "First Dependency: $FIRST_DEPENDENCY_PACKAGE"
# Filter and extract multiple values
ALL_DEPENDENCIES=$(echo "$JSON_DATA" | jq -r '.dependencies[].package')
echo "All Dependencies:
$ALL_DEPENDENCIES"
# Conditional extraction (e.g., get debugMode if it exists)
DEBUG_MODE=$(echo "$JSON_DATA" | jq -r '.config.debugMode // "false"')
echo "Debug Mode: $DEBUG_MODE"
How it works: This script demonstrates using `jq` to parse and extract data from a JSON string or file. It covers extracting top-level and nested values, accessing array elements, iterating over array items, and providing default values for potentially missing keys, making it indispensable for handling configuration or API responses in bash.