首頁·終端機命令

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