Communitygithub.com

JantonioFC/skillsbank

JSONクエリ、フィルタリング、変換、パイプライン統合におけるjqのエキスパートな使用法。実践的なシェルワークフローのためのパターンを提供します。

skillsbank とは?

このスキルは、JSONデータのクエリと変換を行うための標準CLIツールである`jq`のエキスパートレベルの使用法をカバーします。APIやCLIツール(AWS、GitHub、kubectl、docker等)からのJSON出力の解析、構造の変換、値の集約、シェルパイプラインへの組み込みなど、実際の開発ワークフローで即座に活用できるコピー&ペースト可能な例を豊富に提供します。特に、深くネストされたデータのフィルタリング、`select`を使った条件抽出、`map`や`reduce`による変換・集約、文字列補間やCSV/TSV形式へのフォーマット、シェル変数の安全な注入方法など、実践的なパターンを網羅しています。また、`--arg`や`--argjson`を用いたシェル変数の安全な受け渡し、`-r`(raw出力)や`-c`(コンパクト出力)オプションの適切な使い方、`empty`を使った要素の除去など、ベストプラクティスにも焦点を当てています。このスキルは、JSONを多用するあらゆるCLIベースの開発環境(bash、Linuxシェル、GitHub Actions等)で役立ちます。

対応✓Claude Code~Codex CLI✓Cursor✓Gemini CLI
npx skills add https://github.com/JantonioFC/skillsbank/tree/HEAD/skills/jq

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

jq — JSONクエリと変換

概要

jqは、JSONをクエリし、再整形するための標準的なCLIツールです。このスキルは、実践的かつエキスパートレベルの使用法をカバーします:深くネストされたデータのフィルタリング、構造の変換、値の集約、そしてシェルパイプラインへのjqの組み込み。すべての例は、実際のワークフローでそのままコピー&ペーストして使えます。

このスキルを使うべき時

  • 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)]'

# フィールドが存在し、かつnullでないことを確認
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'

実践的なシェル統合

# ファイルから読み込み
jq '.users' data.json

# コンパクト出力(空白なし)でさらにパイプ処理
jq -c '.[]' records.json | while IFS= read -r record; do
  echo "Processing: $record"
done

# シェル変数をjqに渡す
STATUS="active"
jq --arg s "$STATUS" '[.[] | select(.status == $s)]'

# 数値を渡す
jq --argjson threshold 42 '[.[] | select(.value > $threshold)]'

# 複数のJSON行を配列にスラープ
jq -s '.' records.ndjson

# 複数ファイル:すべてを1つの配列にスラープ
jq -s 'add' file1.json file2.json

# コマンドからのNullセーフなパイプライン
kubectl get pods -o json | jq '.items[] | {name: .metadata.name, status: .status.phase}'

# GitHub CLI: PR番号を抽出
gyro 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]})'

# 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の結果をシェル変数や他のコマンドに渡すときは、JSONの文字列引用符を除去するために常に-r(raw出力)を使用する
  • シェル変数を安全に注入するために--arg / --argjsonを使用する — フィルター文字列にシェル変数を直接展開しない
  • 可読性のために[.[] | f]よりもmap(f)を推奨
  • 改行区切りJSONパイプラインでは-c(コンパクト)を使用する。人間が読むデバッグの場合は省略する
  • スクリプトに埋め込む前に、jq -nとリテラル入力を使って対話的にフィルターをテストする
  • nullにフィルタリングするのではなく、不要な要素を削除するにはemptyを使用する

セキュリティと安全性に関する注意

  • jqは設計上読み取り専用です — ファイルに書き込んだりコマンドを実行したりすることはできません
  • 信頼できないJSONフィールド値をシェルコマンドに直接埋め込まないでください。常に引用符で囲むか、--argを使用してください

よくある落とし穴

  • 問題: jqが期待した値の代わりにnullを出力する 解決策: キー名のタイプミスを確認してください。keysを使用して実際のフィールド名を検査してください。JSONは大文字小文字を区別することを覚えておいてください。

  • 問題: 出力で数値が文字列として引用符で囲まれている 解決策: 数値を注入するときは--argの代わりに--argjsonを使用してください。

  • 問題: ターミナルではフィルターが動作するが、スクリプトでは失敗する 解決策: フィルター文字列がシェルで変数展開を防ぐためにシングルクォートを使用していることを確認してください。例: jq '.field' は正しく、jq ".field" は間違いです。

  • 問題: addが空の配列に対してnullを返す 解決策: デフォルト値を提供するためにadd // 0またはadd // ""を使用してください。

  • 問題: 大きなファイルのストリーミングが遅い 解決策: 非常に大きなファイルにはjq --streamを使用するか、jstream/gronに切り替えてください。

関連スキル

  • @bash-pro — jq呼び出しを堅牢なシェルスクリプトでラップする
  • @bash-linux — 一般的なシェルパイプラインパターン
  • @github-automation — GitHub CLIのJSON出力でjqを使用する

制限事項

  • このスキルは、タスクが上記の範囲に明確に一致する場合にのみ使用してください。
  • 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
  • 必要な入力、権限、安全境界、成功基準が不足している場合は、立ち止まって明確化を求めてください。

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.

関連スキル