BASH
Parse JSON API Response and Extract Data with JQ
A bash snippet demonstrating how to use `curl` to fetch a JSON API response and `jq` to parse, filter, and extract specific data fields from it.
#!/bin/bash
API_URL="https://jsonplaceholder.typicode.com/posts/1" # Example API endpoint
echo "Fetching data from $API_URL..."
# Fetch JSON data using curl
JSON_RESPONSE=$(curl -s "$API_URL")
# Check if curl was successful
if [ $? -ne 0 ]; then
echo "Error: Failed to fetch data from $API_URL"
exit 1
fi
echo "Full JSON Response:"
echo "$JSON_RESPONSE" | jq '.' # Pretty print the full JSON
echo -e "
Extracting specific fields:"
POST_ID=$(echo "$JSON_RESPONSE" | jq -r '.id')
POST_TITLE=$(echo "$JSON_RESPONSE" | jq -r '.title')
POST_BODY=$(echo "$JSON_RESPONSE" | jq -r '.body' | head -n 10) # Limit body output
echo "Post ID: $POST_ID"
echo "Post Title: $POST_TITLE"
echo "Post Body (first 10 lines):"
echo "$POST_BODY"
How it works: This script demonstrates a common pattern for interacting with REST APIs directly from the command line. It uses `curl -s` (silent mode) to fetch a JSON response from a specified `API_URL`. After fetching, it checks for `curl` errors. It then pipes the JSON output to `jq`, a powerful command-line JSON processor. It shows how to pretty-print the entire JSON for readability and, more importantly, how to extract specific fields like `id`, `title`, and `body` using `jq -r '.field_name'`. This is invaluable for automating tasks that involve consuming web APIs, fetching configuration, or scripting API interactions.