JQ JSON Transform Pipeline CLI

Transform JSON on the command line with jq filters, selecting fields, reshaping objects, and aggregating arrays in pipes.

BashCli Tooling

Code

bashsnippet
35 lines
#!/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

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.