如何根据条件jq查询获得平坦输出?

时间:2016-11-22 02:45:19

标签: json shell jq

我有以下JSON:

[
  {
    "name": "InstanceA",
    "tags": [
      {
        "key": "environment",
        "value": "production"
      },
      {
        "key": "group",
        "value": "group1"
      }
    ]
  },
  {
    "name": "InstanceB",
    "tags": [
      {
        "key": "group",
        "value": "group2"
      },
      {
        "key": "environment",
        "value": "staging"
      }
    ]
  }
]

我试图根据条件value获得key == 'environment'的平坦输出。我已经尝试了select(boolean_expression),但我无法获得所需的输出,例如:

"InstanceA, production"
"InstanceB, staging"

jq是否支持这种输出?如果是的话,该怎么做?

3 个答案:

答案 0 :(得分:3)

例如:

$ jq '.[] | "\(.name), \(.tags | from_entries | .environment)"' input.json

输出:

"InstanceA, production"
"InstanceB, staging"

答案 1 :(得分:1)

jq '.[] | .name + ", " + (.tags[] | select(.key == "environment").value)' f.json

答案 2 :(得分:0)

以下是使用加入

的解决方案
  .[]
| [.name, (.tags[] | if .key == "environment" then .value else empty end)]
| join(", ")