Jq json processing

From findscripter/everything-skills · View interactive version

Jq json processing is an AI agent skill from the GitHub repository findscripter/everything-skills. 当处理 API/CLI/日志输出的 JSON 时使用;用 jq 过滤、转换、聚合并产出结构化结果或 CSV/TSV/原始文本;不适用于写文件或非 JSON 数据。触发词:jq、JSON 解析、JSON 转换

How to use this skill

Skill file

何时使用

适用场景:

不该用的边界:

步骤

  1. 先用 jq 'keys' 或 jq '.' 探查实际结构与字段名(JSON 大小写敏感)。
  2. 用 .field、.[]、.[i] 定位数据,用管道 | 逐级组合过滤器。
  3. 用 select(...) 过滤、map(...)/{...} 转换、add/group_by 聚合。
  4. 输出给 shell 变量或下游命令时加 -r 去引号;NDJSON 管道用 -c。
  5. 注入外部变量一律用 --arg(字符串)/--argjson(数字、布尔、JSON),切勿把 shell 变量直接拼进过滤器字符串。

指令

示例

# 提取字段
echo '{"name":"alice","age":30}' | jq '.name'        # "alice"

# 过滤管理员并收回数组
echo '[{"role":"admin"},{"role":"user"},{"role":"admin"}]' \
  | jq '[.[] | select(.role == "admin")]'

# 求和一个字段
jq '[.[].price] | add'

# 安全注入 shell 变量(字符串用 --arg,数字用 --argjson)
STATUS="active"
jq --arg s "$STATUS" '[.[] | select(.status == $s)]'
jq --argjson threshold 42 '[.[] | select(.value > $threshold)]'

# 转 CSV(-r 去引号)
jq -r '.[] | [.name, .age, .email] | @csv'

# 对象的数组 -> 数组的对象
# 输入: {"names":["a","b"],"scores":[10,20]}
jq '[.names, .scores] | transpose | map({name: .[0], score: .[1]})'

# 与外部 CLI 串联
kubectl get pods -o json | jq '.items[] | {name: .metadata.name, status: .status.phase}'
gh pr list --json number,title | jq -r '.[] | "\(.number)\t\(.title)"'
aws ec2 describe-instances \
  | jq -r '.Reservations[].Instances[] | select(.State.Name=="running") | .InstanceId'

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT 许可)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.