如何使用jq解析此字符串?

时间:2018-08-27 14:13:14

标签: arrays json jq aws-cli

当我尝试使用jq提取时,CommandID字符串的行为不像我期望的那样:

aws ssm send-command --document-name "AWS-RunPatchBaseline" --instance-ids i-xxxxxxxxxxxx --max-errors "1" --parameters '{"Operation":["Install"]}' --timeout-seconds 600 --output-s3-bucket-name "ssm" --region "us-east-1" | jq

未选择的输出:

    {
  "Command": {
    "CommandId": "7312718d-2327-43g4-bffc-093a0901a13c",
    "DocumentName": "AWS-RunPatchBaseline",
    "Comment": "",
    "ExpiresAfter": 1535382731.286,
    "Parameters": {
      "Operation": [
        "Install"
      ]
    },
    "InstanceIds": [
      "i-xxxxxxxxx"
    ],
    "Targets": [],
    "RequestedDateTime": 1535378531.286,
    "Status": "Pending",
     "StatusDetails": "Pending",
    "OutputS3BucketName": "ssm",
    "OutputS3KeyPrefix": "",
    "MaxConcurrency": "50",
    "MaxErrors": "1",
     "TargetCount": 1,
    "CompletedCount": 0,
    "ErrorCount": 0,
    "ServiceRole": "",
    "NotificationConfig": {
      "NotificationArn": "",
      "NotificationEvents": [],
      "NotificationType": ""
    }
  }
}

我以为我可以使用此命令来获取CommandID字符串:

aws ssm send-command --document-name "AWS-RunPatchBaseline" --instance-ids i-xxxxxxxxxxxxxx --max-errors "1" --parameters '{"Operation":["Install"]}' --timeout-seconds 600 --output-s3-bucket-name "ssm" --region "us-east-1" | jq -r '.Command[].CommandID'

但这给了我这个错误:

 jq: error (at <stdin>:33): Cannot index string with string "CommandID"

关于如何提取该内容的任何想法?

2 个答案:

答案 0 :(得分:1)

"Command"键的值不是列表;它只是另一个以CommandID作为键的对象。你只想要

... | jq -r '.Command.CommandID'

过滤器.Command[]返回对象的序列,因此,由于尝试评估类似"7312718d-2327-43g4-bffc-093a0901a13c".Command而不是{{1 }}。

答案 1 :(得分:0)

似乎您的JSON命令中不是数组对象。

如果需要CommandId的值,请将jq更改为'jq .Command.CommandId'