在JQ中选择多个条件

时间:2016-11-15 16:07:53

标签: json jq

我刚刚开始使用jq json解析器,无论如何选择多个select? 我有这个:

cat file | jq -r '.Instances[] | {ip: .PrivateIpAddress, name: .Tags[]}
                               | select(.name.Key == "Name")'

我还需要包含.name.Key == "Type"

这是JSON:

{
  "Instances": [
    {
      "PrivateIpAddress": "1.1.1.1",
      "Tags": [
        {
          "Value": "Daily",
          "Key": "Backup"
        },
        {
          "Value": "System",
          "Key": "Name"
        },
        {
          "Value": "YES",
          "Key": "Is_in_Domain"
        },
        {
          "Value": "PROD",
          "Key": "Type"
        }
      ]
    }
  ]
}

这是当前的输出:

{
  "ip": "1.1.1.1",
  "name": "System"
}
{
  "ip": "2.2.2.2",
  "name": "host"
}
{
  "ip": "3.3.3.3",
  "name": "slog"
}

期望的输出:

{
  "ip": "1.1.1.1",
  "name": "System",
  "type": "PROD"
}
{
  "ip": "2.2.2.2",
  "name": "host",
  "type": "PROD"
}
{
  "ip": "3.3.3.3",
  "name": "slog",
  "type": "PROD"
}

这样做的正确方法是什么?感谢。

1 个答案:

答案 0 :(得分:2)

没有“正确”的方法可以做到这一点,但有一些方法可以让事情变得更容易。

标签已经采用简单转换为对象的格式(它们是对象条目)。将标记转换为对象以便于访问属性。

$ jq '.Instances[]
    | .Tags |= from_entries
    | {
        ip:   .PrivateIpAddress,
        name: .Tags.Name,
        type: .Tags.Type
      }' file