BASH

Parse and Extract Data from JSON with `jq`

Learn how to use `jq` in Bash to efficiently parse JSON output from APIs or files, extracting specific fields and transforming data for scripting.

#!/bin/bash

# Example: Fetching user data from an API and extracting specific fields
API_URL="https://jsonplaceholder.typicode.com/users/1"

# Fetch JSON and pipe to jq to extract name and email
USER_DATA=$(curl -s "$API_URL" | jq -r '{name: .name, email: .email}')

if [ -z "$USER_DATA" ]; then
  echo "Failed to fetch or parse user data."
  exit 1
fi

USER_NAME=$(echo "$USER_DATA" | jq -r '.name')
USER_EMAIL=$(echo "$USER_DATA" | jq -r '.email')

echo "Fetched User Details:"
echo "Name: $USER_NAME"
echo "Email: $USER_EMAIL"

# Example: Extracting all titles from a list of posts
# curl -s "https://jsonplaceholder.typicode.com/posts" | jq -r '.[].title'
How it works: This script demonstrates using the powerful `jq` tool to parse JSON data within Bash. It fetches JSON from a public API using `curl` and then pipes the output to `jq`. `jq` is used to selectively extract specific fields (name and email in this case) from the JSON object, making it easy to integrate JSON data into shell scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs