BASH

Parse JSON with JQ in Bash

Learn to parse and extract specific data from JSON output using the powerful `jq` command-line JSON processor in your Bash scripts for API integration and data processing.

#!/bin/bash

# This script demonstrates how to parse JSON data using 'jq'.
# Make sure 'jq' is installed (e.g., sudo apt install jq or sudo yum install jq).

# Example JSON data (can be from a file, a variable, or an API call)
JSON_DATA='{
  "name": "Web Developer",
  "skills": [
    {"skill_name": "JavaScript", "level": "Expert"},
    {"skill_name": "Python", "level": "Intermediate"}
  ],
  "experience_years": 5,
  "is_remote_friendly": true
}'

echo "Original JSON data:"
echo "$JSON_DATA" | jq '.'

echo "
Extracting 'name':"
NAME=$(echo "$JSON_DATA" | jq -r '.name')
echo "Name: $NAME"

echo "
Extracting 'experience_years':"
YEARS=$(echo "$JSON_DATA" | jq -r '.experience_years')
echo "Experience Years: $YEARS"

echo "
Extracting the first skill_name (array index 0):"
FIRST_SKILL=$(echo "$JSON_DATA" | jq -r '.skills[0].skill_name')
echo "First Skill: $FIRST_SKILL"

echo "
Listing all skill_names:"
ALL_SKILLS=$(echo "$JSON_DATA" | jq -r '.skills[].skill_name')
echo "All Skills:
$ALL_SKILLS"

# Example with an actual API call (uncomment to test)
# API_URL="https://jsonplaceholder.typicode.com/todos/1"
# echo "
Fetching data from $API_URL and extracting title:"
# TODO_TITLE=$(curl -s "$API_URL" | jq -r '.title')
# echo "Todo Title: $TODO_TITLE"

exit 0
How it works: This script showcases the utility of `jq`, a lightweight and flexible command-line JSON processor. It demonstrates how to parse JSON data, whether it's stored in a variable or fetched from an API using `curl`. The examples illustrate extracting scalar values (`.name`, `.experience_years`), accessing elements within arrays (`.skills[0].skill_name`), and iterating over arrays to list all values (`.skills[].skill_name`). The `-r` flag is used to output raw strings without JSON quotation marks, making it ideal for scripting tasks involving API responses or configuration files.

Need help integrating this into your project?

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

Hire DigitalCodeLabs