BASH
Parse API JSON Responses with JQ
Use a bash script with `jq` to extract, filter, and transform specific data from JSON API responses, enabling efficient command-line data processing and automation.
#!/bin/bash
# Configuration Variables
API_URL="https://jsonplaceholder.typicode.com/posts/1"
echo "Fetching data from $API_URL..."
# Fetch JSON data using curl and pipe to jq for parsing
# Example 1: Extract a specific field
echo "
--- Extracting 'title' field ---"
curl -s "$API_URL" | jq '.title'
# Example 2: Extract multiple fields into a custom format
API_URL_MULTI="https://jsonplaceholder.typicode.com/users"
echo "
--- Extracting 'id', 'name', and 'email' for users ---"
curl -s "$API_URL_MULTI" | jq -r '.[] | "ID: \(.id), Name: \(.name), Email: \(.email)"'
# Example 3: Filter objects based on a condition
# (e.g., users with an ID greater than 5)
echo "
--- Users with ID > 5 ---"
curl -s "$API_URL_MULTI" | jq '.[] | select(.id > 5) | {id, name, email}'
# Example 4: Count items in an array
API_URL_COMMENTS="https://jsonplaceholder.typicode.com/comments?postId=1"
echo "
--- Number of comments for postId 1 ---"
curl -s "$API_URL_COMMENTS" | jq 'length'
# Example 5: Parse a nested field
API_URL_USER_DETAILS="https://jsonplaceholder.typicode.com/users/1"
echo "
--- Extracting user's city ---"
curl -s "$API_URL_USER_DETAILS" | jq '.address.city'
echo "
JQ parsing examples finished."
How it works: This script demonstrates how to effectively parse JSON data received from web APIs using the powerful command-line JSON processor, `jq`. It uses `curl -s` to fetch JSON from various endpoints (like `jsonplaceholder.typicode.com`) and pipes the output directly to `jq`. The examples show how to extract single fields (`.title`), format multiple fields (`-r '.[] | "ID: \(.id), Name: \(.name)"'`), filter arrays based on conditions (`select(.id > 5)`), count array elements (`length`), and access nested fields (`.address.city`). `jq` is an indispensable tool for web developers for quick API interaction, debugging, and integrating API data into shell scripts.