BASH

Parse JSON with jq for API Response Extraction

Efficiently extract specific values from JSON data returned by API calls using the powerful 'jq' command-line JSON processor in Bash scripts.

#!/bin/bash

# Example JSON data (e.g., from an API response via curl)
JSON_DATA='{
  "id": "prod_K2X9R0Z1W3Y4",
  "name": "Premium Widget",
  "price": 29.99,
  "details": {
    "category": "electronics",
    "weight_kg": 0.5
  },
  "tags": ["new", "featured", "bestseller"]
}'

echo "Original JSON data:
$JSON_DATA
"

# 1. Extract a simple top-level value
PRODUCT_ID=$(echo "$JSON_DATA" | jq -r '.id')
echo "Product ID: $PRODUCT_ID"

# 2. Extract a nested value
PRODUCT_CATEGORY=$(echo "$JSON_DATA" | jq -r '.details.category')
echo "Product Category: $PRODUCT_CATEGORY"

# 3. Extract an element from an array (first element)
FIRST_TAG=$(echo "$JSON_DATA" | jq -r '.tags[0]')
echo "First Tag: $FIRST_TAG"

# 4. Check if a key exists (jq -e exits with 0 if found, 1 if not)
if echo "$JSON_DATA" | jq -e '.inventory_count' >/dev/null; then
  echo "'inventory_count' key exists."
else
  echo "'inventory_count' key does NOT exist."
fi

# 5. Extract multiple values and format output
PRODUCT_SUMMARY=$(echo "$JSON_DATA" | jq -r '{name: .name, price: .price, category: .details.category} | .name + ": $" + (.price|tostring) + " in " + .category')
echo "Product Summary: $PRODUCT_SUMMARY"
How it works: This script demonstrates using `jq`, a powerful command-line JSON processor, to parse and extract specific data from JSON strings, typically received from API responses. It shows how to extract simple top-level values, navigate nested objects, access array elements, and check for the existence of keys. The `-r` flag ensures raw string output without quotes, which is useful for direct use in Bash variables. This is an essential tool for integrating Bash scripts with web APIs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs