jqは「空」の値のみをフィルタリングします。

jqは「空」の値のみをフィルタリングします。

AWS CloudWatchログペイロード(CLIコマンドで作成)を含むjsonファイルがあります。 jqを使用しようとしています。ただ「retentionInDays」フィールドを持たない項目の値を返します。以下があり、私が望む方法ですべてを返しますが、tentionInDaysの結果をフィルタリングできないようです。

# Working output (unfiltered)
jq ".logGroups[] | { log_name: .logGroupName, log_arn: .arn, retention_scheme: .retentionInDays }" cwlogs.json

いくつか試しましたが、エラーが発生したり何も出力せずに完了します。

# Doesn't return anything
jq '.logGroups[] | { log_name: .logGroupName, log_arn: .arn, retention_scheme: select(.retentionInDays | contains ("null")?) }' cwlogs.json

# Errors with "jq: error (at cwlogs.json:760): number (7) and string ("null") cannot have their containment checked"
jq '.logGroups[] | { log_name: .logGroupName, log_arn: .arn, retention_scheme: select(.retentionInDays | contains ("null")) }' cwlogs.json

# Hangs forever
jq '.logGroups[] | select(.retentionInDays != "null").type' 

アップデート:私が使用しているJSONのテスト可能な部分

{
    "logGroups": [
        {
            "storedBytes": 0,
            "metricFilterCount": 0,
            "creationTime": 1234,
            "logGroupName": "/aws/elasticbeanstalk/docker",
            "retentionInDays": 7,
            "arn": "longarnhere"
        },
        {
            "storedBytes": 0,
            "metricFilterCount": 0,
            "creationTime": 1245,
            "logGroupName": "/aws/elasticbeanstalk/nginx",
            "arn": "longarnhere"
        }
    ]
}

ベストアンサー1

私はあなたがlogGroups全くキーのないアイテムを手に入れたいと思います。retentionInDays

$ jq '.logGroups[] | select( has("retentionInDays") == false )' file.json
{
  "storedBytes": 0,
  "metricFilterCount": 0,
  "creationTime": 1245,
  "logGroupName": "/aws/elasticbeanstalk/nginx",
  "arn": "longarnhere"
}

次のセットが必要な場合(可能な場合は2つ以上がある可能性があります):

$ jq '.logGroups | map(select( has("retentionInDays") == false ))' file.json
[
  {
    "storedBytes": 0,
    "metricFilterCount": 0,
    "creationTime": 1245,
    "logGroupName": "/aws/elasticbeanstalk/nginx",
    "arn": "longarnhere"
  }
]

has("retentionInDays") | not代わりに使用することもできますhas("retentionInDays") == false

おすすめ記事