mcpField
J
jq-json-processing

jq-json-processing

github.com/laurigates数据与数据库59234 次安装1 天前更新
代码仓库

关于 jq-json-processing

面向命令行 JSON 处理的 jq 技能,适合编写管道和脚本的用户。内容涵盖查询、筛选、转换、验证与故障排查,并提供常见模式示例。

主要功能

  1. 01查询和筛选 JSON
  2. 02转换与合并数据结构
  3. 03验证 JSON 语法和结构
  4. 04提取字段并遍历嵌套数据
  5. 05处理 null 和缺失键
  6. 06排查错误及慢查询

适用场景

  1. 01检查 curl 或 gh 返回的 API 数据
  2. 02在 Shell 管道中筛选记录
  3. 03从 JSON 提取配置值
  4. 04分析嵌套数据和日志

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/laurigates/claude-plugins --skill jq-json-processing

安装后在 Claude Code 中输入/jq-json-processing确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

evals.json
references/
common-patterns.md
troubleshooting.md

详细介绍

jq JSON 处理

使用轻量灵活的命令行 JSON 处理器 jq,专业地处理、查询和转换 JSON 数据。

何时使用此技能

在以下情况下使用此技能……在以下情况下改用 yq-yaml-processing……
提取或筛选 JSON 输入中的字段处理 YAML 文件(Kubernetes、GH Actions、Helm)
解析 gh、curl 或 kubectl -o json 的响应就地编辑 YAML,同时保留注释
在极简镜像中运行 CI 流水线(jq 几乎总是已安装)在处理前将 YAML 转换为 JSON
在以下情况下使用此技能……在以下情况下改用 nushell-data-processing……
用单个表达式完成一次性流水线转换跨 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 声明变量,让查询更清晰
  • 在 shell 脚本中添加注释
  • 将多行 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

资源

评论

支持 Markdown