【问题标题】:Using jq select to filter json not working使用 jq select 过滤 json 不起作用
【发布时间】:2016-09-06 22:37:51
【问题描述】:

我正在尝试使用 jq 从 json 文档中获取属性。我想获取具有特定名称的最新快照。这是 bash 中的 jq 语句,在我添加带有过滤器的选择之前,它工作正常

snapid=aws redshift describe-cluster-snapshots --region us-west-2 | jq'.[] | select(.ClusterIdentifier=="dev-cluster") | max_by(.SnapshotCreateTime) | .SnapshotIdentifier'

这是我从中提取的 json 文档。快照条目不止一个,但这是我的目标。

{
    "Snapshots": [        
        {
                "EstimatedSecondsToCompletion": 0, 
                "OwnerAccount": "45645641155", 
                "CurrentBackupRateInMegaBytesPerSecond": 6.2857, 
                "ActualIncrementalBackupSizeInMegaBytes": 22.0, 
                "NumberOfNodes": 3, 
                "Status": "available", 
                "VpcId": "myvpc", 
                "ClusterVersion": "1.0", 
                "Tags": [], 
                "MasterUsername": "ayxbizops", 
                "TotalBackupSizeInMegaBytes": 192959.0, 
                "DBName": "dev", 
                "BackupProgressInMegaBytes": 22.0, 
                "ClusterCreateTime": "2016-09-06T15:56:08.170Z", 
                "RestorableNodeTypes": [
                    "dc1.large"
                ], 
                "EncryptedWithHSM": false, 
                "ClusterIdentifier": "dev-cluster", 
                "SnapshotCreateTime": "2016-09-06T16:00:25.595Z", 
                "AvailabilityZone": "us-west-2c", 
                "NodeType": "dc1.large", 
                "Encrypted": false, 
                "ElapsedTimeInSeconds": 3, 
                "SnapshotType": "manual", 
                "Port": 5439, 
                "SnapshotIdentifier": "thismorning"
        }
    ]
}

我收到错误,无法使用字符串“ClusterIdentifier”索引数组。

【问题讨论】:

  • 过滤器的开头可能应该是.Snapshots[] | ...
  • @JeffMercado 将此作为答案,以便我将其标记为正确答案。谢谢!
  • 在这种情况下,我认为将其关闭作为一个简单的错字会更合适。否则,如果您愿意,欢迎您自行回答。

标签: json bash jq


【解决方案1】:

这个怎么样?

jq '.[]|map(select(.ClusterIdentifier=="dev-cluster"))
    |max_by(.SnapshotCreateTime)|.SnapshotIdentifier'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 2023-03-17
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多