首页·终端命令

jq

文本处理

用法

jq '[filter]' [file.json]

用自带的一套小语言过滤和重塑 JSON;它常常不是默认装好的,而去掉字符串引号要靠 -r。

常用选项

选项含义
-rRaw output, so strings come out without quotes
-cOne compact line per result
-eSet the exit status from the result, for scripts
--argPass a shell string in as a jq variable
-sSlurp the whole input into one array
-nStart from null input and build output yourself

示例

curl -s api/users | jq -r '.[].name'

Every name, unquoted, one per line.

jq '.items | length' data.json

Counts the entries in an array.

jq -c '.[] | {id, name}' big.json

Two fields per row, compact.

它们本来就是用管道串起来用的。串三条往往比让一条命令做完所有事更短。

怎么看

  • 方括号 [ ] 表示这部分可以不写。
  • 省略号 … 表示可以写多个。
  • 选项区分大小写——有些命令里 -r 和 -R 不是一回事。

常见问题

Q. jq 是做什么的?

用自带的一套小语言过滤和重塑 JSON;它常常不是默认装好的,而去掉字符串引号要靠 -r。

Q. 怎么写?

jq '[filter]' [file.json] —— 方括号表示可以省略的部分。

Q. 值得记的选项有几个?

这里列了 6 个,完整列表在 man jq。这条命令属于文本处理。

相关命令

man 手册: man jq