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