BASH

Extract Data from JSON API Responses with jq

Learn how to quickly parse and extract specific data fields from JSON responses returned by web APIs using the powerful command-line JSON processor `jq`.

#!/bin/bash
# Example: Fetch user data from a public API and extract specific fields
API_URL="https://jsonplaceholder.typicode.com/users/1"

echo "Fetching data from $API_URL..."
RESPONSE=$(curl -s "$API_URL")

if [ $? -ne 0 ]; then
    echo "Error: Failed to fetch data from API." >&2
    exit 1
fi

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

# Extract specific fields using jq
USER_NAME=$(echo "$RESPONSE" | jq -r '.name')
USER_EMAIL=$(echo "$RESPONSE" | jq -r '.email')
USER_CITY=$(echo "$RESPONSE" | jq -r '.address.city')

if [ -z "$USER_NAME" ]; then
    echo "Error: Could not extract user name. JSON response might be invalid or unexpected." >&2
    exit 1
fi

echo "User Name: $USER_NAME"
echo "User Email: $USER_EMAIL"
echo "User City: $USER_CITY"
How it works: This script demonstrates fetching JSON data from a public API using `curl` and then parsing it with `jq`. It extracts the user's name, email, and city. `jq` is an indispensable tool for manipulating JSON from the command line, crucial for scripting interactions with RESTful APIs in shell environments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs