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"
Report a problem with this exampleOpens a pre-filled issue on GitHub.