mcpField
J
jq

jq

github.com/lanej数据与数据库4168 次安装今天更新
代码仓库

关于 jq

jq 是用于筛选和转换 JSON 数据的命令行工具技能,面向编写数据处理命令的用户。它整理了常用过滤语法、流式处理方式和错误排查方法。

主要功能

  1. 01过滤与转换 JSON
  2. 02原始或紧凑格式输出
  3. 03处理 NDJSON 与大型 JSON
  4. 04构建和注入命令行参数
  5. 05诊断常见解析错误

适用场景

  1. 01从 JSON 中提取字段
  2. 02逐条筛选 NDJSON 记录
  3. 03校验 JSON 文件格式
  4. 04安全地将 shell 参数传入过滤器

安装

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

$npx skills add https://github.com/lanej/dotfiles --skill jq

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

详细介绍

jq

过滤器语法与文档所述一致。本文件介绍工具的选择,以及避免常见故障模式的惯用写法。

何时不该使用 jq

  • CSV/TSV → xsv;YAML → yq;对 JSON 执行分析型 SQL → duckdb(read_json_auto)。
  • 不支持原地编辑。请先写入临时文件再移动;jq '...' f.json > f.json 会在 jq 读取输入前将其截断。

值得掌握的惯用写法

jq -r '.name'                     # raw string output — no surrounding quotes
jq -c '.'                         # compact; required when piping NDJSON onward
jq '.field // "default"'          # alternative operator — survives null/missing
jq '.maybe?'                      # suppress "cannot index" instead of erroring out
jq --arg env prod '.[$env]'       # inject shell values; never interpolate into the filter string
jq -n --argjson d "$JSON" '$d.x'  # no input, build from arguments
jq -r '.[] | [.a, .b] | @csv'     # @csv / @tsv / @sh handle quoting correctly
jq 'to_entries | map(...) | from_entries'   # operate on keys
jq 'walk(if type == "object" then del(.secret) else . end)'   # recursive edit

Slurp 与流式处理

-s 会将整个输入读入一个数组,使用方便,但会将所有内容加载到内存中。对于大型输入或 NDJSON,请改为逐条记录处理:

jq -c 'select(.important)' stream.ndjson    # one object per line, streaming
jq --stream 'select(length == 2)' huge.json # leaf-level streaming for a single huge document

在任何 group_by/sort_by 操作之前尽早过滤,因为这些操作必须将整个集合载入内存。

诊断错误

消息原因
parse error: Invalid numeric literalJSON 格式错误——使用 jq empty file.json 验证
Cannot index string with string在非对象上访问字段;使用 jq 'type' 检查
Cannot iterate over null缺少字段;使用 .field // []

jq empty file.json 是快速有效性检查——没有输出即表示有效。debug 会将中间值打印到 stderr,不会影响输出流。

评论

支持 Markdown