jq
文本处理
用法
jq '[filter]' [file.json]用自带的一套小语言过滤和重塑 JSON;它常常不是默认装好的,而去掉字符串引号要靠 -r。
常用选项
| 选项 | 含义 |
|---|---|
| -r | Raw output, so strings come out without quotes |
| -c | One compact line per result |
| -e | Set the exit status from the result, for scripts |
| --arg | Pass a shell string in as a jq variable |
| -s | Slurp the whole input into one array |
| -n | Start from null input and build output yourself |
示例
curl -s api/users | jq -r '.[].name'Every name, unquoted, one per line.
jq '.items | length' data.jsonCounts the entries in an array.
jq -c '.[] | {id, name}' big.jsonTwo fields per row, compact.
它们本来就是用管道串起来用的。串三条往往比让一条命令做完所有事更短。
怎么看
- 方括号 [ ] 表示这部分可以不写。
- 省略号 … 表示可以写多个。
- 选项区分大小写——有些命令里 -r 和 -R 不是一回事。
常见问题
Q. jq 是做什么的?
用自带的一套小语言过滤和重塑 JSON;它常常不是默认装好的,而去掉字符串引号要靠 -r。
Q. 怎么写?
jq '[filter]' [file.json] —— 方括号表示可以省略的部分。
Q. 值得记的选项有几个?
这里列了 6 个,完整列表在 man jq。这条命令属于文本处理。
相关命令
man 手册: man jq