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