shell jqコマンドの活用

jsonを扱うときに非常に役立つjqコマンドのサンプルです。


まずjsonとして下記を準備します。


3つのデータを扱うサンプルです。

それぞれの項目を取得するサンプルは下記です。

echo ‘{“items”:[{"id":1,"name":"test1","value":1000},{"id":2,"name":"test2","vaule":2000},{"id":3,"name":"test3","vaule":3000}]}’ \
| jq -r ‘.items[] | .id’

echo ‘{“items”:[{"id":1,"name":"test1","value":1000},{"id":2,"name":"test2","vaule":2000},{"id":3,"name":"test3","vaule":3000}]}’ \
| jq -r ‘.items[] | .name’

echo ‘{“items”:[{"id":1,"name":"test1","value":1000},{"id":2,"name":"test2","value":2000},{"id":3,"name":"test3","value":3000}]}’ \
| jq -r ‘.items[].value’

集計

echo ‘{“items”:[{"id":1,"name":"test1","value":1000},{"id":2,"name":"test2","value":2000},{"id":3,"name":"test3","value":3000}]}’ \
| jq -r ‘[.items[].value] | add’


Bookmark this on Yahoo Bookmark
Bookmark this on Google Bookmarks
Share on LinkedIn
LINEで送る
Pocket