JQ JSON Transform Pipeline CLI
Transform JSON on the command line with jq filters, selecting fields, reshaping objects, and aggregating arrays in pipes.
Code
#!/usr/bin/env bash
set -euo pipefail
# 输入:带元数据的部署状态 JSON
readonly SAMPLE='[
{"service": "api", "replicas": 3, "healthy": 3, "region": "eu"},
{"service": "billing", "replicas": 4, "healthy": 2, "region": "eu"},
{"service": "search", "replicas": 2, "healthy": 2, "region": "na"}
]'
# 字段选择与对象重塑:输出紧凑的行式报告
echo "$SAMPLE" | jq -r '.[]
| select(.healthy < .replicas)
| "\(.service) degraded: \(.healthy)/\(.replicas) in \(.region)"'
# 聚合统计:全部副本与亚健康服务数
echo "$SAMPLE" | jq '{
total_replicas: (map(.replicas) | add),
degraded: (map(select(.healthy < .replicas)) | length),
regions: (map(.region) | unique)
}'
# 按区域分组汇总
echo "$SAMPLE" | jq -r 'group_by(.region)[]
| "\(.[0].region): \(length) 个服务, 共 \(map(.replicas) | add) 副本"'
# 管道组合:先过滤再排序再取字段
echo "$SAMPLE" | jq -r 'sort_by(-(.replicas)) | .[:2] | .[].service'
# 从文件批量提取并输出 CSV 行
echo "$SAMPLE" | jq -r '.[]
| [.service, (.replicas|tostring), (.healthy|tostring)] | @csv' \
> status.csv
echo "written: $(wc -l < status.csv) rows"
How it works
set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.
The work is delegated to readonly, chained through 18 pipes so each stage’s output feeds the next.
Watch out for
- The pipeline is 18 stages deep — when it misbehaves, split the pipe and test the stages separately.
The key statements that remain
| select(.healthy < .replicas)
| "\(.service) degraded: \(.healthy)/\(.replicas) in \(.region)"'
total_replicas: (map(.replicas) | add),
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `readonly` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.