Communitygithub.com

JantonioFC/skillsbank

專業 jq 使用技巧,用於 JSON 查詢、過濾、轉換及管線整合。提供可在真實 Shell 工作流程中直接使用的實用模式。

skillsbank 是什麼?

此技能涵蓋 jq 的專業級用法,jq 是標準的 CLI 工具,用於查詢和重塑 JSON 資料。技能內容包括:過濾深度巢狀資料、轉換結構、彙總數值,以及將 jq 整合到 Shell 管線中。所有範例皆可直接用於真實工作流程。此技能特別適合在需要解析 API、CLI 工具(如 AWS、GitHub、kubectl、docker)或日誌檔案的 JSON 輸出時使用;或是在需要轉換 JSON 結構(如重新命名鍵、扁平化陣列、分組記錄)時使用。也適用於需要在 bash 腳本或單行指令中使用 `jq`,或解釋複雜 `jq` 表達式的情境。此技能可在支援標準 CLI 工具的任何平台上使用,如 Claude Code、Cursor 或 Codex。

相容平台✓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) is \(.age) years old"'

# 格式化為 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 "Processing: $record"
done

# 將 Shell 變數傳入 jq
STATUS="active"
jq --arg s "$STATUS" '[.[] | select(.status == $s)]'

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

# 將多行 JSON 合併為一個陣列(slurp)
jq -s '.' records.ndjson

# 多個檔案:將所有檔案合併為一個陣列
jq -s 'add' file1.json file2.json

# 來自指令的 null 安全管線
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 — 將 jq 呼叫包裹在穩健的 Shell 腳本中
  • @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.

相關技能