BASH
Parse and Query JSON Data with jq
Efficiently parse, filter, and transform JSON data from API responses or files directly within your bash scripts using the powerful jq tool.
#!/bin/bash
# Ensure jq is installed: sudo apt install jq / brew install jq
JSON_DATA='{"user": {"id": 123, "name": "Alice", "email": "[email protected]", "roles": ["admin", "editor"]}, "status": "active"}'
echo "Original JSON:"
echo "$JSON_DATA" | jq .
echo "
Extracting user name:"
echo "$JSON_DATA" | jq -r '.user.name'
echo "
Checking if user is admin:"
IS_ADMIN=$(echo "$JSON_DATA" | jq -r '.user.roles[] | select(. == "admin")')
if [ -n "$IS_ADMIN" ]; then
echo "User is an admin."
else
echo "User is not an admin."
fi
echo "
Filtering and projecting data (id and email):"
echo "$JSON_DATA" | jq '{userId: .user.id, userEmail: .user.email}'
echo "
Fetching data from a hypothetical API endpoint and parsing:"
# curl -s "https://api.example.com/users/1" | jq '.data.username'
How it works: This snippet demonstrates how to leverage `jq`, a lightweight and flexible command-line JSON processor, within bash scripts. It shows examples of pretty-printing JSON, extracting specific field values, checking for array elements, and creating new JSON objects by projecting and transforming existing data. `jq` is indispensable for working with JSON output from APIs, configuration files, or other services, making it easy to integrate JSON processing directly into shell workflows.