Communitygithub.com

JantonioFC/skillsbank

熟练使用 jq 进行 JSON 查询、过滤、转换和管道集成。提供适用于真实 Shell 工作流的实用模式。

skillsbank 是什么?

本技能专注于 `jq` 工具的高级用法,`jq` 是用于查询和转换 JSON 数据的标准命令行工具。它涵盖了从基础选择、过滤(`select`)、映射和转换,到聚合、字符串插值、键路径操作和条件处理等所有内容。每个示例都设计为可直接复制粘贴,适用于从 API 响应解析、CI/CD 管道到日常 Shell 脚本的各种实际工作流。该技能支持与 AWS CLI、GitHub CLI、kubectl、Docker 等工具的输出进行集成,并提供了将结果安全地注入 Shell 变量的最佳实践。通过使用 `--arg`、`--argjson` 和 `-r` 等选项,用户可以避免常见的陷阱,并构建健壮、高效的自动化脚本。

兼容平台✓Claude Code~Codex CLI✓Cursor✓Gemini CLI
npx skills add https://github.com/JantonioFC/skillsbank/tree/HEAD/skills/jq

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

jq — JSON 查询与转换

概述

jq 是用于查询和重塑 JSON 的标准 CLI 工具。本技能涵盖实用、专家级别的用法:过滤深度嵌套的数据、转换结构、聚合值以及将 jq 组合到 Shell 管道中。每个示例都可直接复制粘贴,适用于真实工作流。

何时使用此技能

  • 当解析来自 API、CLI 工具(AWS、GitHub、kubectl、docker)或日志文件的 JSON 输出时
  • 当需要转换 JSON 结构时(重命名键、展平数组、分组记录)
  • 当用户需要在 bash 脚本或单行命令中使用 jq 时
  • 当需要解释复杂 jq 表达式的作用时

工作原理

jq 接受一个过滤器表达式并将其应用于 JSON 输入。过滤器通过管道符 (|) 组合,jq 原生支持数组、对象、字符串、数字、布尔值和 null。

基础选择

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

# 嵌套访问
echo '{"user":{"email":"[email protected]"}}' | jq '.user.email'

# 数组索引
echo '[10, 20, 30]' | jq '.[1]'
# 20

# 数组切片
echo '[1,2,3,4,5]' | jq '.[2:4]'
# [3, 4]

# 所有数组元素
echo '[{"id":1},{"id":2}]' | jq '.[]'

使用 select 过滤

# 仅保留匹配的元素
echo '[{"role":"admin"},{"role":"user"},{"role":"admin"}]' \
  | jq '[.[] | select(.role == "admin")]'

# 数字比较
curl -s https://api.github.com/repos/owner/repo/issues \
  | jq '[.[] | select(.comments > 5)]'

# 测试字段是否存在且非空
jq '[.[] | select(.email != null)]'

# 组合条件
jq '[.[] | select(.active == true and .score >= 80)]'

映射与转换

# 从每个数组元素中提取字段
echo '[{"name":"alice","age":30},{"name":"bob","age":25}]' \
  | jq '[.[] | .name]'
# ["alice", "bob"]

# 简写:map()
jq 'map(.name)'

# 每个元素构建一个新对象
jq '[.[] | {user: .name, years: .age}]'

# 添加计算字段
jq '[.[] | . + {senior: (.age > 28)}]'

# 重命名键
jq '[.[] | {username: .name, email_address: .email}]'

聚合与归约

# 求和所有值
echo '[1, 2, 3, 4, 5]' | jq 'add'
# 15

# 对对象中的某个字段求和
jq '[.[].price] | add'

# 统计元素数量
jq 'length'

# 最大值 / 最小值
jq 'max_by(.score)'
jq 'min_by(.created_at)'

# reduce:自定义累加器
echo '[1,2,3,4,5]' | jq 'reduce .[] as $x (0; . + $x)'
# 15

# 按字段分组
jq 'group_by(.department)'

# 每组计数
jq 'group_by(.status) | map({status: .[0].status, count: length})'

字符串插值与格式化

# 字符串插值
jq -r '.[] | "\(.name) 年龄 \(.age)"'

# 格式化为 CSV(无表头)
jq -r '.[] | [.name, .age, .email] | @csv'

# 格式化为 TSV
jq -r '.[] | [.name, .score] | @tsv'

# URL 编码值
jq -r '.query | @uri'

# Base64 编码
jq -r '.data | @base64'

处理键和路径

# 列出所有顶级键
jq 'keys'

# 检查键是否存在
jq 'has("email")'

# 删除某个键
jq 'del(.password)'

# 从每个元素中删除嵌套键
jq '[.[] | del(.internal_id, .raw_payload)]'

# 递归下降:在树中任意位置查找某个键的所有值
jq '.. | .id? // empty'

# 获取所有叶子路径
jq '[paths(scalars)]'

条件语句与错误处理

# if-then-else
jq 'if .score >= 90 then "A" elif .score >= 80 then "B" else "C" end'

# 替代运算符:如果为 null 或 false 则使用后备值
jq '.nickname // .name'

# try-catch:跳过错误而不是停止
jq '[.[] | try .nested.value catch null]'

# 使用 // empty 抑制 null 输出
jq '.[] | .optional_field // empty'

实用 Shell 集成

# 从文件读取
jq '.users' data.json

# 紧凑输出(无空格)以便进一步通过管道处理
jq -c '.[]' records.json | while IFS= read -r record; do
  echo "正在处理: $record"
done

# 将 Shell 变量传入 jq
STATUS="active"
jq --arg s "$STATUS" '[.[] | select(.status == $s)]'

# 传入数字
jq --argjson threshold 42 '[.[] | select(.value > $threshold)]'

# 将多行 JSON 拉取为一个数组
jq -s '.' records.ndjson

# 多个文件:将所有文件拉取到一个数组中
jq -s 'add' file1.json file2.json

# 来自命令的空安全管道
kubectl get pods -o json | jq '.items[] | {name: .metadata.name, status: .status.phase}'

# GitHub CLI:提取 PR 编号
gh pr list --json number,title | jq -r '.[] | "\(.number)\t\(.title)"'

# AWS CLI:列出正在运行的实例 ID
aws ec2 describe-instances \
  | jq -r '.Reservations[].Instances[] | select(.State.Name=="running") | .InstanceId'

# Docker:显示容器名称和镜像
docker inspect $(docker ps -q) | jq -r '.[] | "\(.Name)\t\(.Config.Image)"'

高级模式

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

# 展平一层
jq 'flatten(1)'

# 按字段去重
jq 'unique_by(.email)'

# 排序、去重并重新索引
jq '[.[] | .name] | unique | sort'

# walk:递归地将转换应用于每个节点
jq 'walk(if type == "string" then ascii_downcase else . end)'

# env:在 jq 内部读取环境变量
export API_KEY=secret
jq -n 'env.API_KEY'

最佳实践

  • 当将 jq 结果传递给 Shell 变量或其他命令时,始终使用 -r(原始输出)以去除 JSON 字符串的引号
  • 使用 --arg / --argjson 安全地注入 Shell 变量——切勿直接在过滤器字符串中内插 Shell 变量
  • 推荐使用 map(f) 替代 [.[] | f] 以提高可读性
  • 对于换行符分隔的 JSON 管道,使用 -c(紧凑输出);在调试时省略它以获得人类可读的输出
  • 在嵌入脚本之前,先使用 jq -n 和字面输入交互式测试过滤器
  • 使用 empty 来丢弃不需要的元素,而不是将其过滤为 null

安全与注意事项

  • jq 在设计上是只读的——它不能写入文件或执行命令
  • 避免将不受信任的 JSON 字段值直接嵌入到 Shell 命令中;始终使用引号或 --arg

常见陷阱

  • 问题: jq 输出了 null 而不是期望的值 解决方案: 检查键名中的拼写错误;使用 keys 检查实际的字段名称。请记住 JSON 是区分大小写的。

  • 问题: 输出中的数字被引号括起来作为字符串 解决方案: 在注入数字值时,使用 --argjson 而不是 --arg。

  • 问题: 过滤器在终端中有效,但在脚本中失败 解决方案: 确保过滤器字符串在 Shell 中使用单引号,以防止变量展开。示例:jq '.field' 而不是 jq ".field"。

  • 问题: add 在空数组上返回 null 解决方案: 使用 add // 0 或 add // "" 提供后备默认值。

  • 问题: 流式处理大文件很慢 解决方案: 使用 jq --stream 或对于非常大的文件改用 jstream/gron。

相关技能

  • @bash-pro — 在健壮的 Shell 脚本中封装 jq 调用
  • @bash-linux — 通用 Shell 管道模式
  • @github-automation — 将 jq 与 GitHub CLI JSON 输出结合使用

限制

  • 仅当任务明确匹配上述范围时才使用此技能。
  • 不要将输出视为环境特定验证、测试或专家评审的替代品。
  • 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

JantonioFC/skillsbank

AI-powered image editing with style transfer and object removal

JantonioFC/skillsbank

Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.

JantonioFC/skillsbank

Analise e auditoria de editais de leilao judicial e extrajudicial. Riscos ocultos, clausulas perigosas, debitos, ocupante e classificacao da oportunidade.

JantonioFC/skillsbank

Embed Photopea in web apps using photopea.js. Covers embedding, file I/O, scripting, exporting, layers, text, filters, and the full Photoshop-compatible API.

JantonioFC/skillsbank

Best practices for Remotion - Video creation in React

JantonioFC/skillsbank

Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays

JantonioFC/skillsbank

Seek and analyze video content using Memories.ai Large Visual Memory Model for persistent video intelligence

JantonioFC/skillsbank

Writes complete, structured landing pages optimized for SEO ranking, AEO citation, and visitor conversion. Activate when the user wants to write or generate a landing page for a product, service, or offer.

JantonioFC/skillsbank

Video and audio perception, indexing, and editing. Ingest files/URLs/live streams, build visual/spoken indexes, search with timestamps, edit timelines, add overlays/subtitles, generate media, and create real-time alerts.

JantonioFC/skillsbank

Upload, stream, search, edit, transcribe, and generate AI video and audio using the VideoDB SDK.

JantonioFC/skillsbank

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

JantonioFC/skillsbank

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

JantonioFC/skillsbank

Tool lifecycle UI components for React/Next.js from ui.inference.sh. Display tool calls: pending, progress, approval required, results. Capabilities: tool status, progress indicators, approval flows, results display. Use for: showing agent tool calls, human-in-the-loop approvals, tool output. Triggers: tool ui, tool calls, tool status, tool approval, tool results, agent tools, mcp tools ui, function calling ui, tool lifecycle, tool pending

JantonioFC/skillsbank

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

JantonioFC/skillsbank

When the user wants help with paid advertising campaigns on Google Ads, Meta (Facebook/Instagram), LinkedIn, Twitter/X, or other ad platforms. Also use when the user mentions 'PPC,' 'paid media,' 'ROAS,' 'CPA,' 'ad campaign,' 'retargeting,' 'audience targeting,' 'Google Ads,' 'Facebook ads,'...

JantonioFC/skillsbank

Create AI avatar and talking head videos with OmniHuman, Fabric, PixVerse via inference.sh CLI. Models: OmniHuman 1.5, OmniHuman 1.0, Fabric 1.0, PixVerse Lipsync. Capabilities: audio-driven avatars, lipsync videos, talking head generation, virtual presenters. Use for: AI presenters, expla...

JantonioFC/skillsbank

Create AI marketing videos for ads, promos, product launches, and brand content. Models: Veo, Seedance, Wan, FLUX for visuals, Kokoro for voiceover. Types: product demos, testimonials, explainers, social ads, brand videos. Use for: Facebook ads, YouTube ads, product launches, brand awarene...

JantonioFC/skillsbank

Generate AI videos with Google Veo, Seedance, Wan, Grok and 40+ models via inference.sh CLI. Models: Veo 3.1, Veo 3, Seedance 1.5 Pro, Wan 2.5, Grok Imagine Video, OmniHuman, Fabric, HunyuanVideo. Capabilities: text-to-video, image-to-video, lipsync, avatar animation, video upscaling, fole...

JantonioFC/skillsbank

Production-ready CI/CD configurations for Playwright — GitHub Actions, GitLab CI, CircleCI, Azure DevOps, Jenkins, Docker, parallel sharding, reporting, code coverage, and global setup/teardown.

JantonioFC/skillsbank

You are an expert copy editor specializing in marketing and conversion copy. Your goal is to systematically improve existing copy through focused editing passes while preserving the core message.

相关技能