BASH

Extracting Data from JSON API Responses with jq

Learn to efficiently parse and query JSON data returned from web APIs using the powerful 'jq' command-line tool within your bash scripts, enabling quick data extraction.

#!/bin/bash

# Requires 'jq' - install with: sudo apt-get install jq (Debian/Ubuntu) or brew install jq (macOS)

API_URL="https://jsonplaceholder.typicode.com/todos/1"

echo "Fetching data from: $API_URL"

# Fetch JSON data using curl and pipe it to jq
RESPONSE=$(curl -s "$API_URL")

if [ -z "$RESPONSE" ]; then
  echo "Error: No response received from API." >&2
  exit 1
fi

# Pretty print the full JSON response (optional)
# echo "Full JSON Response:"
# echo "$RESPONSE" | jq .

# Extract specific fields using jq
TITLE=$(echo "$RESPONSE" | jq -r '.title')
USER_ID=$(echo "$RESPONSE" | jq -r '.userId')
COMPLETED=$(echo "$RESPONSE" | jq -r '.completed')

# Extracting multiple fields with a single jq command
echo "--- Extracted Details ---"
echo "Title: $TITLE"
echo "User ID: $USER_ID"
echo "Completed: $COMPLETED"

echo "
Multiple fields using one jq command:"
echo "$RESPONSE" | jq -r '"Title: \(.title), User ID: \(.userId), Completed: \(.completed)"'

# Example for an array response (e.g., first element's title from a list of todos)
# curl -s "https://jsonplaceholder.typicode.com/todos" | jq -r '.[0].title'
How it works: This snippet demonstrates how to interact with a JSON API and extract specific data fields using `curl` and `jq`. `curl -s` fetches the data silently, and the output is piped to `jq`. The `-r` flag in `jq` outputs raw strings, removing quotes. You can access nested fields using dot notation (e.g., `.title`) and even construct custom output strings by combining fields. This is invaluable for automating tasks that rely on parsing API responses.

Need help integrating this into your project?

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

Hire DigitalCodeLabs