よく使うjqコマンド

概要

jqコマンドでよく使うものをまとめておきます。

jsonサンプル

{
   "Fruits": [
      {
         "Id": 1,
         "Name": "Apple",
         "Color": "Red"
      },
      {
         "Id", 2,
         "Name": "Banana",
         "Color": "Yellow"
      },
      {
         "Id": 3,
         "Name": "Orange",
         "Color": "Orange"
      }
   ]
}

テキスト出力

❯ /bin/cat example.json | jq -r ".Fruits[].Name"
Apple
Banana
Orange

特定のキーとバリューを抽出

❯ /bin/cat example.json | jq ".Fruits[].Id"
1
2
3

複数のキーとバリューを抽出

❯ /bin/cat example.json | jq ".Fruits[] | { Id: .Id, Name: .Name }"
{
  "Id": 1,
  "Name": "Apple"
}
{
  "Id": 2,
  "Name": "Banana"
}
{
  "Id": 3,
  "Name": "Orange"
}

特定の文字列を含む検索

$ aws rds describe-db-engine-versions | jq '.DBEngineVersions[] | select ( .DBEngineVersionDescription | contains("MySQL 8")) | { EngineVersion, DBEngineVersionDescription }'
{
  "EngineVersion": "8.0.mysql_aurora.3.01.0",
  "DBEngineVersionDescription": "Aurora MySQL 3.01.0 (compatible with MySQL 8.0.23)"
}
{
  "EngineVersion": "8.0.mysql_aurora.3.01.1",
  "DBEngineVersionDescription": "Aurora MySQL 3.01.1 (compatible with MySQL 8.0.23)"
}

特定の文字列を含む検索(複数の文字列のand条件)

$ aws rds describe-db-engine-versions | jq '.DBEngineVersions[] | select ( .DBEngineVersionDescription | contains("MySQL 8") and contains("Aurora")) | { EngineVersion, DBEngineVersionDescription }'
{
  "EngineVersion": "8.0.mysql_aurora.3.01.0",
  "DBEngineVersionDescription": "Aurora MySQL 3.01.0 (compatible with MySQL 8.0.23)"
}
{
  "EngineVersion": "8.0.mysql_aurora.3.01.1",
  "DBEngineVersionDescription": "Aurora MySQL 3.01.1 (compatible with MySQL 8.0.23)"
}