Candid photograph of a Linux server terminal with a soft olive-green glow against a dark slate background, conveying a calm technical atmosphere.

Step-by-step guides for system administrators — covering command-line basics, web server setup, and preparation material for technical interviews.

Browse Tutorials

How to use jq for parsing JSON data in shell scripts

jq turns JSON into values a shell script can inspect, transform, and validate. Instead of splitting text around braces and quotes, a filter can select a field, filter an array, or emit tab-separated values for later commands. This is easier to audit than improvised text parsing.

Australian schedules add another wrinkle: Sydney and Melbourne alternate between AEST and AEDT, while Adelaide uses ACST or ACDT and Darwin remains on ACST. For a 9 a.m. handover export, preserve the stated offset unless the report explicitly requires UTC.

Installing jq on Linux workstations and servers

Install jq where the filtering runs. On RHEL, CentOS Stream, and Fedora:

sudo dnf install jq

For Debian or Ubuntu, run sudo apt install jq. Verify the installation with jq --version, and add the package to containers or CI images rather than assuming a workstation has it.

Australian teams often combine on-premises RHEL or Fedora estates with cloud workloads serving Sydney and Melbourne. Include jq in the runtime image for predictable access. Legacy commands may emit DOS-style text. The DOS4GW command reference illustrates that older ecosystem; such output must be converted to valid JSON before jq can process it.

Reading and filtering JSON safely

Start with a file and inspect its top-level keys.

jq -r '.site.name' config.json
jq -r '.servers[] | select(.enabled == true) | .hostname' hosts.json

Object fields use dot notation and brackets for names containing punctuation. The first command prints the site name, while the second prints each enabled server as plain text. The raw output option is important whenever jq output is read by another shell command.

Missing fields produce null rather than text, so test with has("field") or an explicit conditional when a fallback is needed. The alternative operator also replaces false, which can hide a disabled flag, so use if for boolean values.

Comparing jq with other parsing approaches

The right tool depends on the data's shape and how much validation the script needs.

Approach Best suited to Main advantage Important limitation
jq Nested filters and repeatable output Precise field and array selection Must be installed and filters need testing
grep and sed Quick checks in non-JSON logs Minimal dependencies Brackets, escaped strings, and ordering make them unsafe for JSON
Python json module Complex branching and custom types Rich standard library More verbose for small transformations
shell text tools Flat, line-oriented text Simple and fast for suitable input Never reliable for structured JSON

Use jq for nested objects, arrays, and predictable machine output. Use Python when the transformation needs richer control flow, and treat grep or sed as text searches rather than JSON parsers.

Practical recipes for system administration

Short filters are easier to review when each command has one clear purpose.

The @tsv format escapes tabs, newlines, and backslashes, so each record remains on one line with stable fields for while IFS=$'\t' read -r. It preserves booleans as true or false rather than changing them into null.

Use compact JSON when a filtered result is embedded in another payload; jq -c removes insignificant whitespace. When the data describes mounted filesystems, the systemd mount guide covers creating and managing the corresponding units, while jq can extract status fields from a JSON report.

Handling failures and sensitive records

Automation must distinguish malformed JSON from an empty result and from a failed download, so each condition has an intentional exit status.

API responses can contain names, email addresses, IP addresses, or billing identifiers. In Australia, such data may fall under the Privacy Act 1988 and relevant state or territory privacy laws. Restrict access, avoid full payloads in temporary logs, and apply retention rules; email alerts may also engage the Spam Act 2003.

A nmcli bonding walkthrough can support a wider administration runbook, but network-tool output and application JSON need separate parsers. Do not force nmcli's human-formatted output into jq unless it has first been converted into valid JSON.

Building a dependable end-to-end workflow

A dependable script retrieves once, validates the structure, transforms the payload, and emits only the fields needed.

#!/usr/bin/env bash
set -Eeuo pipefail

payload=$(curl -fsSL "${HOSTS_URL:?Set HOSTS_URL}") || {
  printf 'Unable to retrieve hosts\n' >&2
  exit 1
}

jq -e '(.servers | type) == "array"' <<<"$payload" >/dev/null
jq -r '.servers[] | select(.enabled == true) | [.hostname, .region] | @tsv' <<<"$payload"

jq -e turns a failed validation into a non-zero exit, malformed JSON stops the script, and -r prevents JSON quotes from leaking into shell variables. set -o pipefail preserves upstream failures when retrieval and parsing share a pipeline.

The dependable pattern is to retrieve data once, validate its structure, transform it with an explicit filter, and consume only the required fields. That sequence turns malformed JSON or an unexpected response into a controlled failure instead of a partial command.