BASH
Extract Specific Data from JSON Output with jq
Master `jq` to efficiently parse and extract specific data from JSON responses from APIs or command-line tools, making automation simpler.
#!/bin/bash
# Example JSON data (e.g., from a curl request or a file)
JSON_DATA='{
"id": "item_123",
"name": "Example Product",
"price": 29.99,
"details": {
"sku": "PROD-ABC",
"weight": "1.5kg",
"attributes": ["color:red", "size:M"]
},
"tags": ["electronics", "sale"],
"available": true
}'
echo "--- Extracting 'name' field ---"
echo "$JSON_DATA" | jq -r '.name'
echo "
--- Extracting 'sku' from 'details' object ---"
echo "$JSON_DATA" | jq -r '.details.sku'
echo "
--- Extracting all 'tags' as a comma-separated string ---"
echo "$JSON_DATA" | jq -r '.tags | join(", ")'
echo "
--- Extracting the first attribute ---"
echo "$JSON_DATA" | jq -r '.details.attributes[0]'
echo "
--- Filtering objects in an array (if JSON_DATA was an array of objects) ---"
# Example for an array:
# [{"id": 1, "status": "active"}, {"id": 2, "status": "inactive"}]
# echo '[{"id": 1, "status": "active"}, {"id": 2, "status": "inactive"}]' | jq '.[] | select(.status == "active")'
How it works: This snippet demonstrates how to use the powerful `jq` command-line JSON processor to extract specific data from JSON input. It shows examples of retrieving top-level fields, nested fields, array elements, and transforming arrays into strings. `jq` is an indispensable tool for web developers working with APIs and tools that output JSON, allowing for easy parsing and integration into Bash scripts.