BASH

Parse JSON Data from CLI with JQ

Learn to parse and query JSON data directly from the command line using the powerful `jq` utility in your bash scripts, perfect for API interactions or config files.

#!/bin/bash
# Ensure jq is installed: sudo apt-get install jq or brew install jq

# Example JSON data (can also be piped from a file or curl)
JSON_DATA='{
  "name": "My Project",
  "version": "1.0.0",
  "dependencies": [
    {"package": "express", "version": "~4.17.1"},
    {"package": "react", "version": "^17.0.2"}
  ],
  "config": {
    "port": 3000,
    "env": "development"
  }
}'

echo "--- Extracting 'name' and 'version' ---"
PROJECT_NAME=$(echo "$JSON_DATA" | jq -r '.name')
PROJECT_VERSION=$(echo "$JSON_DATA" | jq -r '.version')
echo "Project: $PROJECT_NAME, Version: $PROJECT_VERSION"

echo "
--- Listing all dependencies' packages ---"
echo "$JSON_DATA" | jq -r '.dependencies[].package'

echo "
--- Getting config port ---"
CONFIG_PORT=$(echo "$JSON_DATA" | jq -r '.config.port')
echo "Configured Port: $CONFIG_PORT"

echo "
--- Filtering dependencies to find React ---"
REACT_DEP=$(echo "$JSON_DATA" | jq -r '.dependencies[] | select(.package == "react")')
echo "React Dependency Info: $REACT_DEP"

echo "
--- Pretty-printing a specific object ---"
echo "$JSON_DATA" | jq '.config'
How it works: This script demonstrates how to use `jq`, a lightweight and flexible command-line JSON processor. It shows examples of extracting top-level fields, iterating through array elements, filtering arrays based on conditions, and pretty-printing specific JSON objects. `jq` is invaluable for scripting interactions with REST APIs, parsing configuration files, or processing log data in JSON format directly in your terminal or scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs