jpskill.com
🛠️ 開発・MCP コミュニティ 🔴 エンジニア向け 👤 エンジニア・AI開発者

🛠️ Jq

jq

JSON形式のデータを効率的に検索したり、必要な情報

⏱ コードレビュー 1時間 → 10分

📺 まず動画で見る(YouTube)

▶ 【衝撃】最強のAIエージェント「Claude Code」の最新機能・使い方・プログラミングをAIで効率化する超実践術を解説! ↗

※ jpskill.com 編集部が参考用に選んだ動画です。動画の内容と Skill の挙動は厳密には一致しないことがあります。

📜 元の英語説明(参考)

Expert jq usage for JSON querying, filtering, transformation, and pipeline integration. Practical patterns for real shell workflows.

🇯🇵 日本人クリエイター向け解説

一言でいうと

JSON形式のデータを効率的に検索したり、必要な情報

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o jq.zip https://jpskill.com/download/3046.zip && unzip -o jq.zip && rm jq.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/3046.zip -OutFile "$d\jq.zip"; Expand-Archive "$d\jq.zip" -DestinationPath $d -Force; ri "$d\jq.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して jq.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → jq フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-17
同梱ファイル
1

💬 こう話しかけるだけ — サンプルプロンプト

  • Jq を使って、最小構成のサンプルコードを示して
  • Jq の主な使い方と注意点を教えて
  • Jq を既存プロジェクトに組み込む方法を教えて

これをClaude Code に貼るだけで、このSkillが自動発動します。

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

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":"a@b.com"}}' | 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}]'

集計とReduce

# すべての値を合計する
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番号を抽出する
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]})'

# 1レベルフラット化する
jq 'flatten(1)'

# フィールドでユニークにする
jq 'unique_by(.email)'

# ソート、重複排除、再インデックス
jq '[.[] | .name] | unique | sort'

# ウォーク: すべてのノードに再帰的に変換を適用する
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 output)を使用してください。
  • シェル変数を安全に挿入するには--arg / --argjsonを使用してください。フィルター文字列にシェル変数を直接補間しないでください。
  • 可読性のために[.[] | f]よりもmap(f)を推奨します。
  • 改行区切りのJSONパイプラインには-c(compact)を使用し、人間が読めるデバッグ出力には省略してください。
  • スクリプトに埋め込む前に、jq -nとリテラル入力でフィルターを対話的にテストしてください。
  • 不要な要素を削除するには、nullにフィルタリングするのではなくemptyを使用してください。

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

  • jqは設計上読み取り専用です。ファイルを書き込んだり、コマンドを実行したりすることはできません。
  • 信頼できないJSONフィールド値をシェルに直接埋め込まないでください。
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

jq — JSON Querying and Transformation

Overview

jq is the standard CLI tool for querying and reshaping JSON. This skill covers practical, expert-level usage: filtering deeply nested data, transforming structures, aggregating values, and composing jq into shell pipelines. Every example is copy-paste ready for real workflows.

When to Use This Skill

  • Use when parsing JSON output from APIs, CLI tools (AWS, GitHub, kubectl, docker), or log files
  • Use when transforming JSON structure (rename keys, flatten arrays, group records)
  • Use when the user needs jq inside a bash script or one-liner
  • Use when explaining what a complex jq expression does

How It Works

jq takes a filter expression and applies it to JSON input. Filters compose with pipes (|), and jq handles arrays, objects, strings, numbers, booleans, and null natively.

Basic Selection

# Extract a field
echo '{"name":"alice","age":30}' | jq '.name'
# "alice"

# Nested access
echo '{"user":{"email":"a@b.com"}}' | jq '.user.email'

# Array index
echo '[10, 20, 30]' | jq '.[1]'
# 20

# Array slice
echo '[1,2,3,4,5]' | jq '.[2:4]'
# [3, 4]

# All array elements
echo '[{"id":1},{"id":2}]' | jq '.[]'

Filtering with select

# Keep only matching elements
echo '[{"role":"admin"},{"role":"user"},{"role":"admin"}]' \
  | jq '[.[] | select(.role == "admin")]'

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

# Test a field exists and is non-null
jq '[.[] | select(.email != null)]'

# Combine conditions
jq '[.[] | select(.active == true and .score >= 80)]'

Mapping and Transformation

# Extract a field from every array element
echo '[{"name":"alice","age":30},{"name":"bob","age":25}]' \
  | jq '[.[] | .name]'
# ["alice", "bob"]

# Shorthand: map()
jq 'map(.name)'

# Build a new object per element
jq '[.[] | {user: .name, years: .age}]'

# Add a computed field
jq '[.[] | . + {senior: (.age > 28)}]'

# Rename keys
jq '[.[] | {username: .name, email_address: .email}]'

Aggregation and Reduce

# Sum all values
echo '[1, 2, 3, 4, 5]' | jq 'add'
# 15

# Sum a field across objects
jq '[.[].price] | add'

# Count elements
jq 'length'

# Max / min
jq 'max_by(.score)'
jq 'min_by(.created_at)'

# reduce: custom accumulator
echo '[1,2,3,4,5]' | jq 'reduce .[] as $x (0; . + $x)'
# 15

# Group by field
jq 'group_by(.department)'

# Count per group
jq 'group_by(.status) | map({status: .[0].status, count: length})'

String Interpolation and Formatting

# String interpolation
jq -r '.[] | "\(.name) is \(.age) years old"'

# Format as CSV (no header)
jq -r '.[] | [.name, .age, .email] | @csv'

# Format as TSV
jq -r '.[] | [.name, .score] | @tsv'

# URL-encode a value
jq -r '.query | @uri'

# Base64 encode
jq -r '.data | @base64'

Working with Keys and Paths

# List all top-level keys
jq 'keys'

# Check if key exists
jq 'has("email")'

# Delete a key
jq 'del(.password)'

# Delete nested keys from every element
jq '[.[] | del(.internal_id, .raw_payload)]'

# Recursive descent: find all values for a key anywhere in tree
jq '.. | .id? // empty'

# Get all leaf paths
jq '[paths(scalars)]'

Conditionals and Error Handling

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

# Alternative operator: use fallback if null or false
jq '.nickname // .name'

# try-catch: skip errors instead of halting
jq '[.[] | try .nested.value catch null]'

# Suppress null output with // empty
jq '.[] | .optional_field // empty'

Practical Shell Integration

# Read from file
jq '.users' data.json

# Compact output (no whitespace) for further piping
jq -c '.[]' records.json | while IFS= read -r record; do
  echo "Processing: $record"
done

# Pass a shell variable into jq
STATUS="active"
jq --arg s "$STATUS" '[.[] | select(.status == $s)]'

# Pass a number
jq --argjson threshold 42 '[.[] | select(.value > $threshold)]'

# Slurp multiple JSON lines into an array
jq -s '.' records.ndjson

# Multiple files: slurp all into one array
jq -s 'add' file1.json file2.json

# Null-safe pipeline from a command
kubectl get pods -o json | jq '.items[] | {name: .metadata.name, status: .status.phase}'

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

# AWS CLI: list running instance IDs
aws ec2 describe-instances \
  | jq -r '.Reservations[].Instances[] | select(.State.Name=="running") | .InstanceId'

# Docker: show container names and images
docker inspect $(docker ps -q) | jq -r '.[] | "\(.Name)\t\(.Config.Image)"'

Advanced Patterns

# Transpose an object of arrays to an array of objects
# Input: {"names":["a","b"],"scores":[10,20]}
jq '[.names, .scores] | transpose | map({name: .[0], score: .[1]})'

# Flatten one level
jq 'flatten(1)'

# Unique by field
jq 'unique_by(.email)'

# Sort, deduplicate and re-index
jq '[.[] | .name] | unique | sort'

# Walk: apply transformation to every node recursively
jq 'walk(if type == "string" then ascii_downcase else . end)'

# env: read environment variables inside jq
export API_KEY=secret
jq -n 'env.API_KEY'

Best Practices

  • Always use -r (raw output) when passing jq results to shell variables or other commands to strip JSON string quotes
  • Use --arg / --argjson to inject shell variables safely — never interpolate shell variables directly into filter strings
  • Prefer map(f) over [.[] | f] for readability
  • Use -c (compact) for newline-delimited JSON pipelines; omit it for human-readable debugging
  • Test filters interactively with jq -n and literal input before embedding in scripts
  • Use empty to drop unwanted elements rather than filtering to null

Security & Safety Notes

  • jq is read-only by design — it cannot write files or execute commands
  • Avoid embedding untrusted JSON field values directly into shell commands; always quote or use --arg

Common Pitfalls

  • Problem: jq outputs null instead of the expected value Solution: Check for typos in key names; use keys to inspect actual field names. Remember JSON is case-sensitive.

  • Problem: Numbers are quoted as strings in the output Solution: Use --argjson instead of --arg when injecting numeric values.

  • Problem: Filter works in the terminal but fails in a script Solution: Ensure the filter string uses single quotes in the shell to prevent variable expansion. Example: jq '.field' not jq ".field".

  • Problem: add returns null on an empty array Solution: Use add // 0 or add // "" to provide a fallback default.

  • Problem: Streaming large files is slow Solution: Use jq --stream or switch to jstream/gron for very large files.

Related Skills

  • @bash-pro — Wrapping jq calls in robust shell scripts
  • @bash-linux — General shell pipeline patterns
  • @github-automation — Using jq with GitHub CLI JSON output

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.