BASH
Processing JSON Data in Bash with JQ
Master parsing and manipulating JSON data in Bash scripts using the powerful `jq` command-line JSON processor, essential for API interactions and data extraction.
#!/bin/bash
# Example JSON data (e.g., from an API response)
JSON_DATA='{
"id": "user123",
"name": "Alice Wonderland",
"email": "[email protected]",
"isActive": true,
"roles": ["admin", "editor"],
"lastLogin": "2023-10-26T10:30:00Z",
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
}
}'
echo "Original JSON:"
echo "$JSON_DATA" | jq .
echo -e "
Extracting name:"
NAME=$(echo "$JSON_DATA" | jq -r '.name')
echo "User Name: $NAME"
echo -e "
Extracting all roles:"
ROLES=$(echo "$JSON_DATA" | jq -r '.roles[]')
echo "Roles:"
echo "$ROLES"
echo -e "
Filtering active users (example with a list):"
USERS_LIST='[
{"name": "Alice", "isActive": true},
{"name": "Bob", "isActive": false},
{"name": "Charlie", "isActive": true}
]'
ACTIVE_USERS=$(echo "$USERS_LIST" | jq -r '.[] | select(.isActive == true) | .name')
echo "Active users: $ACTIVE_USERS"
echo -e "
Updating a value and outputting new JSON:"
UPDATED_JSON=$(echo "$JSON_DATA" | jq '.isActive = false | .address.zip = "98765"')
echo "$UPDATED_JSON" | jq .
How it works: This script demonstrates how to parse and manipulate JSON data using `jq`, a lightweight and flexible command-line JSON processor. It covers extracting specific fields, iterating over arrays, filtering data based on conditions, and even updating values to produce modified JSON output. `jq -r` is used to output raw strings without quotes, making it easy to use `jq`'s output in other Bash commands.