BASH

Parse JSON Output with JQ

A bash script demonstrating how to parse and extract specific values from a JSON string or file using the powerful command-line JSON processor, 'jq'.

#!/bin/bash

# Sample JSON data (can also be piped from a file or curl command)
JSON_DATA='{
  "id": "user123",
  "name": "John Doe",
  "email": "[email protected]",
  "isActive": true,
  "details": {
    "role": "developer",
    "projects": ["web-app", "api-service", "mobile-client"],
    "settings": null
  }
}'

# Check if jq is installed
if ! command -v jq &> /dev/null
then
    echo "Error: 'jq' is not installed. Please install it to run this script."
    echo "  On Debian/Ubuntu: sudo apt-get install jq"
    echo "  On macOS: brew install jq"
    exit 1
fi

echo "--- Original JSON Data ---"
echo "$JSON_DATA" | jq .

echo "
--- Extracting Specific Fields ---"
echo "User Name: $(echo "$JSON_DATA" | jq -r '.name')"
echo "User Email: $(echo "$JSON_DATA" | jq -r '.email')"
echo "Is Active: $(echo "$JSON_DATA" | jq -r '.isActive')"

echo "
--- Extracting Nested Fields ---"
echo "User Role: $(echo "$JSON_DATA" | jq -r '.details.role')"

echo "
--- Extracting Array Elements ---"
echo "First Project: $(echo "$JSON_DATA" | jq -r '.details.projects[0]')"
echo "All Projects (raw array): $(echo "$JSON_DATA" | jq -r '.details.projects')"
echo "All Projects (comma-separated): $(echo "$JSON_DATA" | jq -r '.details.projects | join(", ")')"

echo "
--- Conditional Logic/Filtering (Example: Find project starting with 'web') ---"
echo "Project starting with 'web': $(echo "$JSON_DATA" | jq -r '.details.projects[] | select(startswith("web"))')"

echo "
--- Iterating over an Array (Example: prefixing each project) ---"
echo "Projects with prefix:"
echo "$JSON_DATA" | jq -r '.details.projects[] | "- Project: \(. )"'
How it works: This script demonstrates how to effectively parse and extract data from JSON using the powerful `jq` command-line utility. It shows various use cases, including retrieving top-level values, accessing nested objects, selecting elements from arrays, and performing basic array manipulations like joining elements. `jq` is an indispensable tool for web developers working with APIs, configuration files, and any JSON-formatted output in bash scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs