GeekIt

jq命令速查

安装与基础、取值索引、构造修改、数组统计、字符串正则、条件处理、参数传递、实战场景与报错排查等 199 条命令

共 199 条命令 · 11 类场景 · 点击右侧图标可复制

命令 / 片段说明复制
jq --version查看版本,1.6 与 1.7 在部分内置函数上有差异
jq --help查看全部命令行参数
apt install jqDebian/Ubuntu 安装
yum install jqRHEL/CentOS 系安装
brew install jqmacOS 安装
choco install jqWindows 安装
jq '.' file.json格式化并高亮输出,最常用的一条
cat file.json | jq '.'从标准输入读取,管道场景必备
curl -s https://api.example.com/data | jq '.'接口返回直接格式化,排查字段最快
jq -c '.' file.json紧凑输出,一行一个 JSON,日志与存储用
jq -r '.name' file.json原始字符串输出,去掉引号,脚本赋值必用
jq -j '.name' file.json不追加换行,拼接场景用
jq -n '1 + 1'不读输入,直接用表达式生成结果
jq -s '.' a.json b.json把多个文档合并成一个数组
jq -e '.ok' file.json结果非 false/null 时退出码为 0,做条件判断
jq -R '.' access.log按原始文本逐行读取,处理非 JSON 日志
jq --sort-keys '.' file.json键名排序输出,便于 diff 对比
jq --tab '.' file.json用制表符缩进
jq --indent 4 '.' file.json指定缩进空格数
jq --ascii-output '.' file.json非 ASCII 字符转义,兼容老系统
jq --stream '.' big.json流式解析大文件,降低内存占用
jq -C '.' file.json强制彩色输出,重定向到 less 时用
命令 / 片段说明复制
jq '.foo' file.json取顶层字段
jq '.foo.bar' file.json链式取嵌套字段
jq '.foo | .bar' file.json管道写法,等价上一条
jq '."foo-bar"' file.json键名含短横线等特殊字符时加引号
jq '.foo?' file.json字段不存在时不报错,直接输出 null
jq '.items[0]' file.json取数组第一个元素
jq '.items[-1]' file.json取数组最后一个元素
jq '.items[1:3]' file.json切片,取下标 1 到 2 的元素
jq '.items[]' file.json展开数组,逐个输出元素
jq '.items[]?.name' file.json元素为 null 时跳过,避免报错
jq '.items[].name' file.json展开后取字段,注意 .name 要与 [] 分开层级
jq '.. | .id? // empty' file.json递归查找所有 id 字段
jq '.foo // "default"' file.json字段为 null 或 false 时给默认值
jq '.a // .b // "none"' file.json多级兜底,取第一个有值的
jq 'paths' file.json列出所有非空路径,快速摸清结构
jq 'path(.a.b)' file.json把路径表示为数组,配合 getpath 使用
jq 'getpath(["a","b"])' file.json按路径数组取值,路径可动态拼接
jq 'has("foo")' file.json判断字段或下标是否存在
jq 'type' file.json查看值类型:object/array/string/number/boolean/null
jq 'length' file.json对象取字段数、数组取长度、字符串取字符数
jq 'keys' file.json取键名并排序
jq 'keys_unsorted' file.json保留原始顺序的键名
jq 'values' file.json只输出值,丢掉键
命令 / 片段说明复制
jq '{name, age}' file.json同名字段简写,等价 {name: .name, age: .age}
jq '{user: .name, mail: .email}' file.json重命名字段并重组结构
jq '[.items[].id]' file.json把展开结果收集成数组
jq '[.items[] | {id, name}]' file.json投影出精简结构,最常用的清洗手法
jq '.a + .b' file.json数组拼接、对象浅合并、字符串连接
jq '.a * .b' file.json对象深合并,嵌套字段递归合并
jq 'del(.password)' file.json删除敏感字段后再输出
jq 'del(.items[].secret)' file.json批量删除数组元素里的字段
jq '.status = "ok"' file.json直接赋值,不存在则新建
jq '.count |= . + 1' file.json更新管道,基于旧值计算新值
jq '.count += 1' file.json算术自增的简写
jq '.tags += ["new"]' file.json数组追加元素
jq '.name //= "unknown"' file.json为空时才赋值
jq '.items[0].name = "x"' file.json按下标修改数组元素
jq '.items |= map(select(.id != 2))' file.json过滤掉指定元素,等价删除
jq 'to_entries' file.json对象转 key/value 数组,便于遍历
jq 'from_entries' file.jsonkey/value 数组转回对象
jq 'with_entries(.key |= ascii_upcase)' file.json批量转换键名,with_entries 是神器
jq 'with_entries(select(.key != "tmp"))' file.json按 key 过滤字段
jq 'reduce .items[] as $i (0; . + $i.price)' file.json归约求和,做聚合统计
jq 'foreach .items[] as $i (0; . + 1)' file.json逐次输出累积过程
jq '{}' -n生成空对象,脚本里初始化结构用
jq -n '{name: "zs", age: 18}'无输入直接构造 JSON,配合 --arg 更实用
命令 / 片段说明复制
jq 'map(.name)' file.json对数组每个元素做投影
jq 'map_values(. + 1)' file.json对对象每个值做变换
jq '.[] | select(.age > 18)' file.json按条件过滤,注意 select 要放在管道后
jq 'map(select(.status == "ok"))' file.json过滤并保留数组结构
jq 'add' file.json数组求和或拼接
jq 'add / length' file.json计算平均值
jq 'any(.ok == false)' file.json是否存在不满足条件的元素
jq 'all(.ok == true)' file.json是否全部满足条件
jq 'sort' file.json排序,数字按大小、字符串按字典序
jq 'sort_by(.age)' file.json按字段排序
jq 'sort_by(.age) | reverse' file.json降序排列
jq 'group_by(.type)' file.json按字段分组,输出二维数组
jq 'group_by(.type) | map({type: .[0].type, count: length})' file.json分组计数,报表场景最常写的一条
jq 'unique' file.json数组去重
jq 'unique_by(.id)' file.json按字段去重
jq 'min' file.json取最小值,同类还有 max
jq 'min_by(.price)' file.json按字段取最小,另有 max_by
jq 'flatten' file.json把嵌套数组完全展平
jq 'flatten(1)' file.json只展平一层
jq '[range(0; 5)]' -n生成数字序列
jq 'limit(3; .items[])' file.json只取前 3 个元素
jq 'first(.items[])'取第一个元素,last 取最后一个
jq 'nth(1; .items[])'取指定下标元素
jq 'sort_by(-.count) | .[0:10]'取 Top N,配合负号实现降序
命令 / 片段说明复制
jq 'ascii_downcase' file.json转小写,ascii_upcase 转大写
jq 'startswith("http")' file.json前缀判断
jq 'endswith(".com")' file.json后缀判断
jq 'contains("error")'包含判断,数组与对象也可用
jq 'inside("hello world")'判断自身是否被包含
jq -r 'split(",")'按分隔符拆成数组
jq -r 'join(",")'把数组拼成字符串
jq -r '.[] | join(",")'每行输出逗号拼接结果,导出文本常用
jq 'ltrimstr("test-")'去掉前缀,rtrimstr 去后缀
jq 'sub("old"; "new")'替换第一个匹配
jq 'gsub("a"; "b")'全局替换
jq 'gsub("\\s+"; " ")'用正则压缩空白
jq 'gsub("(?<x>[0-9]+)"; "N"')替换时使用命名捕获
jq 'test("^[a-z]+$")'正则匹配,返回布尔值
jq 'test("error"; "i")'带 i 标志忽略大小写
jq 'match("(?<k>id)=(?<v>[0-9]+)")'返回匹配对象,含 captures 数组
jq 'capture("(?<k>[a-z]+)=(?<v>[0-9]+)")'直接得到命名捕获对象,解析日志超好用
jq '[scan("[0-9]+")]'扫描出全部匹配片段
jq '@base64'Base64 编码,@base64d 解码
jq -r '.[] | @csv'转 CSV 行,自动加引号转义
jq -r '.[] | @tsv'转 TSV,适合贴进表格工具
jq -r '@json'把值序列化为 JSON 字符串
jq -r '@uri'URL 编码,拼查询参数时用
jq -r '@sh'输出可直接给 shell 用的转义字符串
jq 'tostring' / jq 'tonumber'字符串与数字互转
jq 'explode' / jq 'implode'字符串与码点数组互转
命令 / 片段说明复制
jq 'numbers'过滤出数字类型,同类还有 strings/arrays/objects/booleans/nulls/scalars
jq 'values'过滤掉 null
jq '[.[] | type]'批量查看元素类型
jq 'floor' / 'ceil' / 'round'向下取整、向上取整、四舍五入
jq 'sqrt' / 'pow(2)'开方与乘方
jq 'fabs'取绝对值
jq 'nan / infinite'特殊数值常量,配合 type 判断
jq 'now | floor'当前时间戳(秒)
jq 'now | todate'时间戳转 ISO8601 字符串
jq 'todate' / jq 'fromdate'时间字符串与时间戳互转
jq 'strftime("%Y-%m-%d %H:%M:%S")'按格式输出时间
jq 'strptime("%Y-%m-%d") | mktime'解析时间字符串为时间戳
jq 'gmtime' / jq 'localtime'时间戳转时间数组,注意时区差异
jq '.[] | .duration | tonumber / 1000'毫秒转秒,指标计算常用
命令 / 片段说明复制
jq 'if .ok then "pass" else "fail" end'条件分支,注意必须有 end
jq 'if .a then 1 elif .b then 2 else 3 end'多分支判断
jq '.foo // "default"'空值兜底,比 if 更简洁
jq '.foo // empty'为空时完全不输出,避免 null 混进结果
jq 'try .foo.bar catch "err"'捕获错误并给替代值
jq '.foo?'可选操作符,出错时返回空
jq 'error("custom message")'主动抛错,配合 -e 做校验
jq 'halt_error(1)'以指定退出码退出,流水线门禁用
jq 'label $out | .[] | if . < 0 then break $out else . end'提前终止遍历
jq -e '.items | length > 0'条件不成立时退出码非 0,可直接用于 if 判断
jq -e '.status == "ok"' && echo pass脚本里的断言写法
jq 'select(.level == "error")'不满足条件时输出为空,常用于日志过滤
命令 / 片段说明复制
jq -n --arg name "zs" '{name: $name}'传字符串变量,避免拼接注入
jq -n --argjson n 42 '{count: $n}'传 JSON 字面量(数字/数组/对象)
jq --arg url "$URL" '.redirect = $url'shell 变量安全注入,推荐替代字符串拼接
jq --slurpfile cfg config.json '$cfg[0].name'整份文件作为变量读入
jq --rawfile text note.txt '{note: $text}'原样读入文本文件作为字符串
jq -r '$ARGS.positional[]' --args a b c读取位置参数
jq -s '.' *.json多个文件合并成数组,做批量统计
jq -s 'add' *.json多个数组文件直接拼成一个大数组
jq -R -s 'split("\n")'把整份文本读成一个字符串再按行拆
jq -R '. | fromjson? // .'逐行尝试解析 JSON,解析失败保留原文
jq -c '.' < data.json从重定向读取,脚本中比管道更稳
jq -c '.' file.json > out.json && mv out.json file.json原地改写文件,先写临时文件避免截断
命令 / 片段说明复制
kubectl get pods -o json | jq -r '.items[].metadata.name'提取所有 Pod 名
kubectl get pods -o json | jq -r '.items[] | "\(.metadata.name)\t\(.status.phase)"'拼成表格,两列对齐输出
kubectl get nodes -o json | jq -r '.items[] | select(.status.conditions[] | select(.type=="Ready") | .status != "True") | .metadata.name'筛出 NotReady 节点
aws ec2 describe-instances | jq -r '.Reservations[].Instances[] | [.InstanceId, .State.Name] | @tsv'云资源清单导出为 TSV
jq -r '.items[] | select(.status == 500) | .path' access.json日志里筛出 500 请求路径
jq -r '.items[] | .user' access.json | sort | uniq -c | sort -rn | head -10Top10 访问用户,jq 加 shell 组合
jq 'group_by(.status) | map({status: .[0].status, n: length})' access.json按状态码统计分布,纯 jq 完成
jq -r '.[] | [.name, .cpu, .mem] | @csv' nodes.json > nodes.csvJSON 转 CSV,交给表格或 BI
jq '.spec.replicas = 3' deploy.json > new.json批量改配置后重新应用
jq 'walk(if type == "string" then gsub("old"; "new") else . end)'递归替换所有字符串,walk 用于深层遍历
jq -n --arg u "$USER" '{"user": $u, "ts": now}'构造带时间戳的请求体或审计记录
jq -e '.[] | select(.name == null)' && echo 有缺失字段数据质量校验
jq '[.[] | .price] | add' orders.json求和金额,报表常用
jq '.[] | select(.tags | index("prod"))' svc.json按数组元素是否包含过滤
jq 'input_filename' a.json b.json输出当前处理的是哪个文件,多文件排查用
命令 / 片段说明复制
curl -s api | jq -c '.[] | {id, name}'最经典的接口数据清洗组合
yq '.spec.replicas' deploy.yamlYAML 请用 yq,jq 只处理 JSON
kubectl get -o json | jq ...优先用 -o json,比解析表格文本可靠
jq -c '.' | wc -l统计记录条数
jq -r '.[] | @sh' | xargs -n1 sh -c生成安全的 shell 参数再批量执行
jq '.' file.json | less -R大文件分页查看,配合 -C 保留颜色
diff <(jq -S . a.json) <(jq -S . b.json)排序后对比两份 JSON 的差异
jq '.' | md5sum计算结构摘要,判断配置是否变化
gojq / jaq追求性能或兼容性可替换实现,语法基本一致
jq --stream超大文件用流式解析,避免一次性载入内存
shell 中程序体用单引号避免 $、反引号被 shell 提前展开
PowerShell 中用双引号并转义Windows 下引号规则不同,容易踩坑
命令 / 片段说明复制
Cannot index string with string "foo"对字符串取字段,先用 type 确认结构层级
Cannot index array with string "x"对数组用字段取值,应写成 .[] 或加下标
Cannot iterate over null展开的对象是 null,加 ? 或先用 // 兜底
parse error: Invalid numeric literal输入不是合法 JSON,常见于日志或多文档拼接
parse error: Expected another key-value pairJSON 本身有语法错误,先用 jq . 单独验证
jq: error: syntax error, unexpected ...程序体引号或括号不匹配,检查 shell 引号转义
jq: error: Top-level program not given只给了文件名忘了过滤表达式
number (1) and string ("a") cannot be added类型不一致,用 tonumber/tostring 转换
Invalid path expressionpath/getpath 参数不是数组形式
--arg 传入的数字仍是字符串需要参与运算时用 tonumber 或改用 --argjson
jq: error (at <stdin>:0): breaklabel/break 用法错误,检查 label 与 break 是否配对
输出中文变成转义序列默认不转义,出现转义说明加了 --ascii-output
结果里混入 null用 // empty 过滤,或在表达式中加 select(. != null)
大文件把内存打满改用 --stream 或先切分文件
管道里 jq 报错但脚本继续跑set -o pipefail 让管道失败暴露出来
Windows 下引号被吃掉PowerShell 会解析单引号内变量,改用双引号并转义 $

运维常用组合

接口数据清洗curl -s https://api.example.com/items | jq -c '.[] | {id, name, status}' | head -20
K8s 资源清单kubectl get pods -A -o json | jq -r '.items[] | [.metadata.namespace, .metadata.name, .status.phase] | @tsv'
日志分组统计jq 'group_by(.status) | map({status: .[0].status, count: length})' access.json
JSON 转 CSVjq -r '.[] | [.name, .cpu, .mem] | @csv' nodes.json > nodes.csv
批量改配置jq '.spec.replicas = 3' deploy.json > new.json && kubectl apply -f new.json
流水线门禁jq -e '.errors | length == 0' report.json && echo pass || echo fail

实战要点

1. 程序体用单引号

shell 里一定要用单引号包住 jq 表达式,否则 $ 与反引号会被提前展开

2. 脚本取值加 -r

不加 -r 会带引号,赋值给变量后拼命令很容易出错

3. 条件判断用 -e

结果非 false/null 时退出码为 0,可直接写 if 与 CI 门禁

4. 空值用 // 兜底

比 if 简洁,且能处理字段缺失导致的 null 与报错

5. 传参别拼字符串

用 --arg/--argjson 注入变量,避免引号与转义带来的注入风险

6. 先看结构再写表达式

用 paths 或 jq . 摸清层级,比反复试错快得多

共 199 条 jq 命令 · 示例中的文件路径与字段名请替换为实际环境

关于jq命令速查

在线 jq 命令速查手册,按安装与基础用法、取值与索引、构造与修改、数组与统计、字符串与正则、类型与数值、条件与错误处理、输入输出与文件、实战场景、与其他工具配合、常见报错与排查等 11 类场景整理 190 余条常用命令与表达式,每条附中文说明与可直接复制的写法,支持关键词搜索、分类折叠和一键复制,打开网页即可查阅。涵盖 jq --version 与 apt/yum/brew/choco 安装与 jq . 格式化与 -c 紧凑输出 与 -r 原始字符串 与 -j 无换行 与 -n null 输入 与 -s slurp 多文档 与 -e 退出码 与 -R 原始输入 与 --arg/--argjson/--slurpfile/--rawfile 传参 与 --sort-keys/--tab/--indent/--ascii-output 与 --stream 流式解析、.foo 与 .foo.bar 与 ."foo-bar" 与 .foo? 容错 与 .[0] 与 .[-1] 与 .[1:3] 与 .[] 与 .[]? 与 .. 递归 与 .foo // "default" 与 // empty 与 path()/getpath()/has()/type/length 与 keys/keys_unsorted/values 与 to_entries/from_entries/with_entries、{name} 简写与 {a: .b} 与 [.items[].id] 与 + 合并与 * 深合并 与 del() 与 =/|=//=/+= 赋值 与 map/map_values/select 与 add/any/all 与 sort/sort_by/group_by/unique/unique_by 与 min/max/min_by/max_by 与 reverse/flatten/range/limit/first/last/nth 与 reduce/foreach、ascii_downcase/ascii_upcase 与 startswith/endswith/contains/inside 与 split/join 与 ltrimstr/rtrimstr 与 sub/gsub 与 test/match/capture/scan 与 @base64/@base64d/@csv/@tsv/@json/@uri/@sh/@text 与 tostring/tonumber 与 explode/implode、numbers/strings/arrays/objects/booleans/nulls/iterables 与 floor/ceil/round/sqrt/pow 与 now/todate/fromdate/strftime/strptime/mktime/gmtime/localtime、if/elif/else/end 与 try-catch 与 error() 与 halt_error() 与 label/break/last,还有 kubectl 与 aws cli 输出解析、日志字段过滤、group_by 统计、@csv 导出、多文件合并、构造请求体、undefined 与 null 处理等实战,以及 Cannot index string with string、Cannot iterate over null、parse error: Invalid numeric literal、syntax error、Top-level program not given、number and string cannot be added、Invalid path expression、--arg 传数字需 tonumber、PowerShell 引号转义 等报错排查。适用于接口返回与日志解析、Kubernetes 与云平台 CLI 输出提取、JSON 转 CSV/表格、配置批量修改、流水线中的结构化数据处理,以及运维、SRE 与后端工程师面试复习。

核心能力

  • 涵盖 jq --version 与 apt/yum/brew/choco 安装与 jq . 格式化与 -c 紧凑输出 与 -r 原始字符串 与 -j 无换行 与 -n null 输入 与 -s slurp 多文档 与 -e 退出码 与 -R 原始输入 与 --arg/--argjson/--slurpfile/--rawfile 传参 与 --sort-keys/--tab/--indent/--ascii-output 与 --stream 流式解析、.foo 与 .foo.bar 与 ."foo-bar" 与 .foo? 容错 与 .[0] 与 .[-1] 与 .[1:3] 与 .[] 与 .[]? 与 .. 递归 与 .foo // "default" 与 // empty 与 path()/getpath()/has()/type/length 与 keys/keys_unsorted/values 与 to_entries/from_entries/with_entries、{name} 简写与 {a: .b} 与 [.items[].id] 与 + 合并与 * 深合并 与 del() 与 =/|=//=/+= 赋值 与 map/map_values/select 与 add/any/all 与 sort/sort_by/group_by/unique/unique_by 与 min/max/min_by/max_by 与 reverse/flatten/range/limit/first/last/nth 与 reduce/foreach、ascii_downcase/ascii_upcase 与 startswith/endswith/contains/inside 与 split/join 与 ltrimstr/rtrimstr 与 sub/gsub 与 test/match/capture/scan 与 @base64/@base64d/@csv/@tsv/@json/@uri/@sh/@text 与 tostring/tonumber 与 explode/implode、numbers/strings/arrays/objects/booleans/nulls/iterables 与 floor/ceil/round/sqrt/pow 与 now/todate/fromdate/strftime/strptime/mktime/gmtime/localtime、if/elif/else/end 与 try-catch 与 error() 与 halt_error() 与 label/break/last,还有 kubectl 与 aws cli 输出解析、日志字段过滤、group_by 统计、@csv 导出、多文件合并、构造请求体、undefined 与 null 处理等实战,以及 Cannot index string with string、Cannot iterate over null、parse error: Invalid numeric literal、syntax error、Top-level program not given、number and string cannot be added、Invalid path expression、--arg 传数字需 tonumber、PowerShell 引号转义 等报错排查

适用场景

适用于接口返回与日志解析、Kubernetes 与云平台 CLI 输出提取、JSON 转 CSV/表格、配置批量修改、流水线中的结构化数据处理,以及运维、SRE 与后端工程师面试复习。jq命令速查全程在浏览器中完成,无需安装插件,可放心用于日常办公与排障。

常见问题

jq命令速查是免费的吗?需要注册或安装吗?
jq命令速查完全免费,无需注册、无需下载安装任何软件,用浏览器打开网页即可直接使用,也不限制使用次数。
jq命令速查支持哪些功能?
涵盖 jq --version 与 apt/yum/brew/choco 安装与 jq . 格式化与 -c 紧凑输出 与 -r 原始字符串 与 -j 无换行 与 -n null 输入 与 -s slurp 多文档 与 -e 退出码 与 -R 原始输入 与 --arg/--argjson/--slurpfile/--rawfile 传参 与 --sort-keys/--tab/--indent/--ascii-output 与 --stream 流式解析、.foo 与 .foo.bar 与 ."foo-bar" 与 .foo? 容错 与 .[0] 与 .[-1] 与 .[1:3] 与 .[] 与 .[]? 与 .. 递归 与 .foo // "default" 与 // empty 与 path()/getpath()/has()/type/length 与 keys/keys_unsorted/values 与 to_entries/from_entries/with_entries、{name} 简写与 {a: .b} 与 [.items[].id] 与 + 合并与 * 深合并 与 del() 与 =/|=//=/+= 赋值 与 map/map_values/select 与 add/any/all 与 sort/sort_by/group_by/unique/unique_by 与 min/max/min_by/max_by 与 reverse/flatten/range/limit/first/last/nth 与 reduce/foreach、ascii_downcase/ascii_upcase 与 startswith/endswith/contains/inside 与 split/join 与 ltrimstr/rtrimstr 与 sub/gsub 与 test/match/capture/scan 与 @base64/@base64d/@csv/@tsv/@json/@uri/@sh/@text 与 tostring/tonumber 与 explode/implode、numbers/strings/arrays/objects/booleans/nulls/iterables 与 floor/ceil/round/sqrt/pow 与 now/todate/fromdate/strftime/strptime/mktime/gmtime/localtime、if/elif/else/end 与 try-catch 与 error() 与 halt_error() 与 label/break/last,还有 kubectl 与 aws cli 输出解析、日志字段过滤、group_by 统计、@csv 导出、多文件合并、构造请求体、undefined 与 null 处理等实战,以及 Cannot index string with string、Cannot iterate over null、parse error: Invalid numeric literal、syntax error、Top-level program not given、number and string cannot be added、Invalid path expression、--arg 传数字需 tonumber、PowerShell 引号转义 等报错排查。
jq命令速查适合哪些场景使用?
适用于接口返回与日志解析、Kubernetes 与云平台 CLI 输出提取、JSON 转 CSV/表格、配置批量修改、流水线中的结构化数据处理,以及运维、SRE 与后端工程师面试复习。