BASH

Efficiently Parse JSON Data from Command Line

Master parsing and extracting specific data from JSON responses or files directly in your Bash scripts using the powerful `jq` command-line JSON processor, ideal for API interactions.

#!/bin/bash

# Example 1: Parsing JSON from a string
JSON_STRING='{"name": "Alice", "age": 30, "city": "New York"}'

echo "Original JSON String: ${JSON_STRING}"

# Extract 'name'
NAME=$(echo "${JSON_STRING}" | jq -r '.name')
echo "Extracted Name: ${NAME}"

# Extract 'age'
AGE=$(echo "${JSON_STRING}" | jq -r '.age')
echo "Extracted Age: ${AGE}"

echo "
---
"

# Example 2: Parsing JSON from a file
# Create a dummy JSON file
cat > data.json << EOF
{
  "users": [
    {
      "id": 1,
      "username": "johndoe",
      "email": "[email protected]"
    },
    {
      "id": 2,
      "username": "janedoe",
      "email": "[email protected]"
    }
  ],
  "metadata": {
    "count": 2,
    "timestamp": "2023-10-27T10:00:00Z"
  }
}
EOF

echo "Parsing JSON from data.json:"

# Extract all usernames
USERNAMES=$(jq -r '.users[].username' data.json)
echo "All Usernames:
${USERNAMES}"

# Extract email of user with id 1
EMAIL_USER1=$(jq -r '.users[] | select(.id == 1).email' data.json)
echo "Email of user with ID 1: ${EMAIL_USER1}"

# Extract timestamp from metadata
TIMESTAMP=$(jq -r '.metadata.timestamp' data.json)
echo "Timestamp: ${TIMESTAMP}"

# Clean up dummy file
rm data.json
How it works: This script demonstrates how to efficiently parse and extract data from JSON strings or files using `jq`, a lightweight and flexible command-line JSON processor. It covers extracting single values, iterating through arrays to get multiple values, and filtering array elements based on conditions. For web developers, `jq` is indispensable for working with API responses, configuration files, and other JSON data directly within Bash scripts, allowing for powerful automation and data manipulation without writing complex parsing logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs