こんにちは、としあきです。
配列になっているJSONデータからデータを検索したい場合、どうすればいいでしょうか?
調べてみるとgnu系コマンドでjqというコマンドがありました。
> jq
目次
Macにjqコマンドをインストール
masOSだとhomebrewでインストールできます。
> brew install gcc
何やらエラーが発生しました。
Warning: Bottle installation failed: building from source.
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
Error: An exception occurred within a child process:
CompilerSelectionError: gmp cannot be built with any available compilers.
Install GNU's GCC:
brew install gcc
macOSアップデート後に発生するもののようです。
xcodeをインストールすれば良いようです。
> xcode-select --install
ダウンロードを始めるのでインストール完了まで行います。
再度インストールしてみますが、エラーが出るので、必要なライブラリをインストールしていったら、jqもインストールできました。
> brew install libtool
> brew install gcc
> brew install jq

JSONデータを出力する
標準入力に入ったJSONをパイプラインで渡します。
整形した形で表示:
> cat data/sample.json | jq
{
"requests": [
{
"lastUpdated": "2021-03-21 23-12-00",
"title": "ある日の出来事",
"author": "Ichiro Tanaka",
"createdDate": "2021-03-21 23-12-00"
},
{
"lastUpdated": "2021-02-10 01-19-00",
"title": "安全保障について",
"author": "Ichiko Aihara",
"createdDate": "2019-01-09 08-54-00"
},
{
"lastUpdated": "2021-05-01 01-03-00",
"title": "研究結果",
"author": "Ikkei Kumada",
"createdDate": "2020-08-31 21-01-00"
}
]
}
配列を表示する
要素名を指定すればその内容が表示されます。
> cat data/sample.json | jq ".requests"
[
{
"lastUpdated": "2021-03-21 23-12-00",
"title": "ある日の出来事",
"author": "Ichiro Tanaka",
"createdDate": "2021-03-21 23-12-00"
},
{
"lastUpdated": "2021-02-10 01-19-00",
"title": "安全保障について",
"author": "Ichiko Aihara",
"createdDate": "2019-01-09 08-54-00"
},
{
"lastUpdated": "2021-05-01 01-03-00",
"title": "研究結果",
"author": "Ikkei Kumada",
"createdDate": "2020-08-31 21-01-00"
}
]
指定した要素のみの一覧を表示する
さらに配列の中で欲しい要素の一覧を取得するには以下のようにします。
> cat data/sample.json | jq ".requests[].lastUpdated"
"2021-03-21 23-12-00"
"2021-02-10 01-19-00"
"2021-05-01 01-03-00"
指定した項目の最大値を表示する
> cat data/sample.json | jq "[.requests[].lastUpdated] | max"
"2021-05-01 01-03-00"
- 最大値を出したい項目の値の配列を作る
- 配列に対してmaxを実行する
要素を並べ替えて表示する
> cat data/sample.json | jq ".requests | sort_by(.lastUpdated)"
[
{
"lastUpdated": "2021-02-10 01-19-00",
"title": "安全保障について",
"author": "Ichiko Aihara",
"createdDate": "2019-01-09 08-54-00"
},
{
"lastUpdated": "2021-03-21 23-12-00",
"title": "ある日の出来事",
"author": "Ichiro Tanaka",
"createdDate": "2021-03-21 23-12-00"
},
{
"lastUpdated": "2021-05-01 01-03-00",
"title": "研究結果",
"author": "Ikkei Kumada",
"createdDate": "2020-08-31 21-01-00"
}
]
配列を出力してその結果に対してsort_byで各要素の並べ替えたい項目名を指定します。
まとめ
jqコマンドが使える環境ならシンプルなコマンドとして検索できますね!