← Back to all snippets
BASH

Parse JSON API Response with JQ in Bash

Learn to extract specific data from a JSON API response using `curl` and `jq` within a bash script, essential for automating API interactions and data processing in web development.

#!/bin/bash

API_URL="https://jsonplaceholder.typicode.com/posts/1" # Example API endpoint

echo "Fetching data from $API_URL..."

# Fetch JSON data using curl and pipe to jq for pretty printing or direct processing
# -s for silent, -o /dev/null for discarding progress meter if not processing
RESPONSE_JSON=$(curl -s "$API_URL")

if [ -z "$RESPONSE_JSON" ]; then
    echo "Error: No response from API or connection failed."
    exit 1
fi

# Check if jq is installed
if ! command -v jq &> /dev/null
then
    echo "Error: jq is not installed. Please install it (e.g., sudo apt install jq)."
    exit 1
fi

# Example 1: Extract a specific field (e.g., 'title')
TITLE=$(echo "$RESPONSE_JSON" | jq -r '.title')
echo "Title: $TITLE"

# Example 2: Extract multiple fields (e.g., 'id' and 'body')
id_and_body=$(echo "$RESPONSE_JSON" | jq -r '.id, .body')
echo "
ID and Body:
$id_and_body"

# Example 3: Extract a nested field from a list (if API_URL returned a list)
# For example, if API_URL was "https://jsonplaceholder.typicode.com/posts" to get the first post's user ID:
# FIRST_POST_USER_ID=$(curl -s "https://jsonplaceholder.typicode.com/posts" | jq -r '.[0].userId')
# echo "
User ID of first post in list: $FIRST_POST_USER_ID"
How it works: This script demonstrates how to interact with a REST API and parse its JSON response using `curl` and the powerful `jq` command-line JSON processor. It fetches data from a specified URL, then uses `jq` to query and extract individual fields like 'title' or multiple fields like 'id' and 'body'. This is highly useful for automating API calls, integrating with web services, and extracting specific data for further processing in shell scripts, making it a cornerstone for backend and DevOps tasks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs