jq-json-processing について
コマンドラインで JSON を扱う人向けの、jq に関するスキルです。クエリ、フィルタリング、変換、検証、トラブルシューティングを実例とともに扱います。
主な機能
- 01JSON のクエリとフィルタリング
- 02データ構造の変換と結合
- 03JSON の構文と構造の検証
- 04フィールド抽出とネストの探索
- 05null と欠落キーへの対応
- 06エラーや遅いクエリの調査
活用シーン
- 01curl や gh の API 応答の確認
- 02シェルパイプラインでのレコード抽出
- 03JSON からの設定値の取得
- 04ネストしたデータやログの分析
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ laurigates/ claude-plugins --skill jq-json-processingインストール後、Claude Code で/jq-json-processingを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
evals.jsonreferences/common-patterns.mdtroubleshooting.md詳細
jq による JSON 処理
軽量で柔軟なコマンドライン JSON プロセッサーである jq を使用して、JSON データを処理、クエリ、変換するための専門知識です。
このスキルを使用する場面
| 次のような場合にこのスキルを使用します… | 次のような場合は代わりに yq-yaml-processing を使用します… |
|---|---|
| JSON 入力からフィールドを抽出またはフィルタリングする | YAML ファイル(Kubernetes、GH Actions、Helm)を扱う |
gh、curl、または kubectl -o json のレスポンスを解析する | コメントを保持したまま YAML を直接編集する |
| jq が広くインストールされている最小イメージ上で CI パイプラインを実行する | 処理前に YAML → JSON に変換する |
| 次のような場合にこのスキルを使用します… | 次のような場合は代わりに nushell-data-processing を使用します… |
|---|---|
| 1 つの式で完結する単発のパイプライン変換 | JSON、YAML、CSV、TOML にまたがる複数ステップの変換 |
| 別のコマンドから標準入力にパイプされた JSON を扱う | 集計、グループ化、または視覚的なテーブル探索 |
主な専門知識
JSON 操作
- パス式を使用して JSON をクエリ、フィルタリングする
- JSON の構造や形状を変換する
- JSON データを結合、マージ、分割する
- JSON の構文と構造を検証する
データ抽出
- JSON オブジェクトから特定のフィールドを抽出する
- 条件に基づいて配列をフィルタリングする
- 入れ子になった JSON 構造をたどる
- null 値や存在しないキーを処理する
基本コマンド
基本的なクエリ
# Pretty-print JSON
jq '.' file.json
# Extract specific field
jq '.fieldName' file.json
# Extract nested field
jq '.user.email' file.json
# Extract array element
jq '.[0]' file.json
jq '.items[2]' file.json
配列操作
# Get array length
jq '.items | length' file.json
# Map over array
jq '.items | map(.name)' file.json
# Filter array
jq '.items[] | select(.active == true)' file.json
jq '.users[] | select(.age > 18)' file.json
# Sort array
jq '.items | sort_by(.name)' file.json
jq '.items | sort_by(.date) | reverse' file.json
# Get first/last elements
jq '.items | first' file.json
jq '.items | last' file.json
# Unique values
jq '.tags | unique' file.json
オブジェクト操作
# Get all keys
jq 'keys' file.json
jq '.config | keys' file.json
# Get all values
jq '.[] | values' file.json
# Select specific fields
jq '{name, email}' file.json
jq '{name: .fullName, id: .userId}' file.json
# Add field
jq '. + {newField: "value"}' file.json
# Delete field
jq 'del(.password)' file.json
# Merge objects
jq '. * {updated: true}' file.json
フィルタリングと条件
# Select with conditions
jq 'select(.status == "active")' file.json
jq '.[] | select(.price < 100)' file.json
# Multiple conditions (AND)
jq '.[] | select(.active and .verified)' file.json
jq '.[] | select(.age > 18 and .country == "US")' file.json
# Multiple conditions (OR)
jq '.[] | select(.type == "admin" or .type == "moderator")' file.json
# Exists / has field
jq '.[] | select(has("email"))' file.json
jq 'select(.optional != null)' file.json
# Not condition
jq '.[] | select(.status != "deleted")' file.json
文字列操作
# String interpolation
jq '"Hello, \(.name)"' file.json
# Convert to string
jq '.id | tostring' file.json
# String contains
jq '.[] | select(.email | contains("@gmail.com"))' file.json
# String starts/ends with
jq '.[] | select(.name | startswith("A"))' file.json
jq '.[] | select(.file | endswith(".json"))' file.json
# Split string
jq '.path | split("/")' file.json
# Join array to string
jq '.tags | join(", ")' file.json
# Lowercase/uppercase
jq '.name | ascii_downcase' file.json
jq '.name | ascii_upcase' file.json
パイプと合成
# Chain operations
jq '.items | map(.name) | sort | unique' file.json
# Multiple filters
jq '.users[] | select(.active) | select(.age > 18) | .email' file.json
# Group by
jq 'group_by(.category)' file.json
jq 'group_by(.status) | map({status: .[0].status, count: length})' file.json
出力形式
# Compact output (no pretty-print)
jq -c '.' file.json
# Raw output (no quotes for strings)
jq -r '.message' file.json
jq -r '.items[] | .name' file.json
# Output as tab-separated values
jq -r '.[] | [.name, .age, .email] | @tsv' file.json
# Output as CSV
jq -r '.[] | [.name, .age, .email] | @csv' file.json
# Output as JSON array on one line
jq -c '[.items[]]' file.json
入出力オプション
# Read from stdin
cat file.json | jq '.items'
curl -s https://api.example.com/data | jq '.results'
# Multiple input files
jq -s '.' file1.json file2.json # Slurp into array
# Write to file
jq '.filtered' input.json > output.json
# In-place edit (use sponge from moreutils)
jq '.updated = true' file.json | sponge file.json
高度なパターン
# Recursive descent
jq '.. | .email? // empty' file.json
# Reduce (sum, accumulate)
jq '[.items[].price] | add' file.json
jq 'reduce .items[] as $item (0; . + $item.price)' file.json
# Variable assignment
jq '.items[] | . as $item | $item.name + " - " + ($item.price | tostring)' file.json
# Conditional (if-then-else)
jq '.items[] | if .price > 100 then "expensive" else "affordable" end' file.json
jq 'if .error then .error else .data end' file.json
# Try-catch for error handling
jq '.items[] | try .field catch "not found"' file.json
# Flatten nested arrays
jq '.items | flatten' file.json
jq '.items | flatten(1)' file.json # Flatten one level
実際の使用例
# Extract all emails from nested structure
jq '.. | .email? // empty' users.json
# Get unique list of all tags across items
jq '[.items[].tags[]] | unique' data.json
# Count items by status
jq 'group_by(.status) | map({status: .[0].status, count: length})' items.json
# Transform API response to simple list
jq '.results[] | {id, name: .full_name, active: .is_active}' response.json
# Filter GitHub workflow runs (recent failures)
gh run list --json status,conclusion,name,createdAt | \
jq '.[] | select(.conclusion == "failure") | {name, createdAt}'
# Extract package.json dependencies with versions
jq '.dependencies | to_entries | map("\(.key)@\(.value)")' package.json
# Merge two JSON files
jq -s '.[0] * .[1]' base.json override.json
# Create summary from log data
jq 'group_by(.level) | map({level: .[0].level, count: length, samples: [.[].message][:3]})' logs.json
ベストプラクティス
クエリの作成
- 簡単なものから始め、段階的に複雑にしていきます
- まず小さなデータセットでフィルターをテストします
- スクリプトでは
-cフラグを使用して出力をコンパクトにします -rフラグを使用して生の文字列(引用符なし)を出力します
パフォーマンス
- パイプラインの早い段階で
select()を使用してデータを絞り込みます - 大きなファイルでは、特定のパスを指定した対象を絞ったクエリを使用します
--streamフラグを使用して大きな JSON をストリーム処理します- 処理を高速化するために
jq -cの使用を検討します
エラー処理
- オプションのアクセスには
?演算子を使用します:.field? // emptyを使用して null やエラーを除外します- エラーを適切に処理するには
try-catchを使用します has("field")でフィールドの存在を確認します
読みやすさ
- 複雑なクエリは複数のステップに分けます
- 明確にするために
as $varで変数を使用します - シェルスクリプトにコメントを追加します
- 複数行の jq プログラムを読みやすく整形します
よく使われるパターン
タスク別のレシピ(API レスポンスの処理、設定の抽出/マージ、ログ分析、CSV ↔ JSON 変換)については、references/common-patterns.md を開いてください。
トラブルシューティング
jq が解析エラーを報告する、何も返さない、型エラーを発生させる、または大きなファイルで処理が遅い場合は、references/troubleshooting.md を開いてください。
他のツールとの連携
# With curl (API calls)
curl -s "https://api.github.com/users/octocat" | jq '.name, .bio'
# With gh CLI (GitHub operations)
gh api repos/owner/repo/issues | jq '.[] | {number, title, state}'
# With find (batch processing)
find . -name "package.json" -exec jq '.version' {} \;
# With xargs (parallel processing)
cat urls.txt | xargs -I {} curl -s {} | jq '.data'
# With yq (YAML to JSON conversion)
yq eval -o=json file.yaml | jq '.specific.field'
クイックリファレンス
演算子
.field- フィールドにアクセスする.[]- 配列/オブジェクトを反復処理する|- パイプ(操作を連結する),- 複数の出力?- オプション(エラーを抑制する)//- 代替演算子(デフォルト値)
関数
keys、values- オブジェクトのキー/値length- 配列/オブジェクト/文字列の長さmap()、select()- 配列操作sort、sort_by()- 並べ替えgroup_by()- グループ化unique- 重複を削除するadd- 数値を合計する、または連結するhas()- フィールドの存在を確認するtype- 値の型を取得する
型変換
tostring、tonumber- 型を変換する@csv、@tsv、@json- 出力形式を指定するsplit()、join()- 文字列/配列を変換する
インストール
# macOS (Homebrew)
brew install jq
# Ubuntu/Debian
sudo apt-get install jq
# Verify installation
jq --version
リソース
- 公式マニュアル:https://stedolan.github.io/jq/manual/
- jq プレイグラウンド:https://jqplay.org/
- チュートリアル:https://stedolan.github.io/jq/tutorial/
コメント
Markdown 対応