BASH

Parse JSON with jq for API Responses or Config

Efficiently parse and extract specific data from JSON responses or configuration files using the powerful 'jq' command-line tool in Bash scripting.

#!/bin/bash

# Example JSON data
JSON_DATA='{"user":{"id":123,"name":"Alice","email":"[email protected]"},"status":"active"}'

echo "Original JSON:"
echo "$JSON_DATA"

# Extract a specific field using dot notation
USER_NAME=$(echo "$JSON_DATA" | jq -r '.user.name')
USER_EMAIL=$(echo "$JSON_DATA" | jq -r '.user.email')

echo "
Extracted User Name: $USER_NAME"
echo "Extracted User Email: $USER_EMAIL"

# Extract all keys at the top level
echo "
All top-level keys:"
echo "$JSON_DATA" | jq -r 'keys[]'

# Filter and extract specific items from an array (hypothetical API response)
# curl -s https://api.example.com/users | jq -r '.[] | select(.status == "active") | .name'
How it works: This Bash snippet demonstrates how to use `jq`, a lightweight and flexible command-line JSON processor, to parse and extract data from JSON strings. It shows basic extraction using dot notation to navigate object properties and retrieve specific values like user name and email. The `-r` flag outputs raw strings without quotes. It also includes an example of listing all top-level keys. This is incredibly useful for processing API responses or configuration files directly in your scripts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs