【问题标题】:How can I use jq to parse this string?如何使用 jq 解析这个字符串?
【发布时间】:2018-08-27 14:13:13
【问题描述】:

当我尝试使用 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"

关于如何提取它的任何想法?

【问题讨论】:

  • 否决了这个问题。请花时间创建mvce
  • 你能告诉我你觉得哪个部分不符合mvce吗?
  • 你能告诉我你在这里简化了什么吗?外壳命令? json 块?尤其是 json blob a) 包含大量不必要的信息,但不是 b) 是有效的 json,这意味着对回答问题没有帮助。
  • 我可能没有通过证明替代变体来为命令添加更多简化,我的假设是它可能会增加混乱,并且任何对 jq 有足够了解的人都可以轻松回答这个问题....发生了什么。
  • 您仍然可以编辑问题。

标签: arrays json jq aws-cli


【解决方案1】:

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

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

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

【讨论】:

  • 最后应该是一个反勾号吗?那或使用单引号似乎不起作用-使用单引号我得到: q: 1 compile error Exception ignored in: <_io.textiowrapper name="<stdout>" mode="w" encoding="UTF-8 "> BrokenPipeError: [Errno 32] 断管
  • 不,只是一个错字。
【解决方案2】:

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

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

【讨论】:

  • 是的哈哈!它躲着我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多