jq - in for循环,创建一个新数组,然后追加键/值对

时间:2016-04-27 01:58:47

标签: bash jq

我需要遍历一个数组(AWS实例ID'),然后拉出标签并使用jq将它们添加到数组中。

我有变量来定义我的需求。在这种情况下:

VolumeId
Tag1Value
Tag2Value
Tag3Value

当我在for循环中迭代时,它们会发生变化。我知道如何创建一个新数组:

jq -n --arg v "$VolumeId" '[{"VolumeId": $v}]'

但是每次都会创建一个新的JSON数组。我需要创建一次,然后在循环过程中追加它。

我正在寻找的输出是一个新创建的JSON数组:

[
  {
    "VolumeId": $VolumeId,
    "Tag1": $Tag1Value,
    "Tag2": $Tag2Value,
    "Tag3": $Tag3Value
  },
  {
    "VolumeId": $VolumeId,
    "Tag1": $Tag1Value,
    "Tag2": $Tag2Value,
    "Tag3": $Tag3Value
  },
  {
    "VolumeId": $VolumeId,
    "Tag1": $Tag1Value,
    "Tag2": $Tag2Value,
    "Tag3": $Tag3Value
  }
]

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

这是一个示例,显示如何将值流(此处为数组流)组合到JSON对象数组中:

(cat << EOF
["VolumeId1", "Tag1Value1", "Tag2Value1", "Tag3Value1"]
["VolumeId2", "Tag1Value2", "Tag2Value2", "Tag3Value2"]
["VolumeId3", "Tag1Value3", "Tag2Value3", "Tag3Value3"]
EOF
) | jq -s 'map( {VolumeId: .[0], Tag1Value: .[1], Tag2Value: .[2],  Tag3Value: .[3] }) '

输出:

[
  {
    "VolumeId": "VolumeId1",
    "Tag1Value": "Tag1Value1",
    "Tag2Value": "Tag2Value1",
    "Tag3Value": "Tag3Value1"
  },
  {
    "VolumeId": "VolumeId2",
    "Tag1Value": "Tag1Value2",
    "Tag2Value": "Tag2Value2",
    "Tag3Value": "Tag3Value2"
  },
  {
    "VolumeId": "VolumeId3",
    "Tag1Value": "Tag1Value3",
    "Tag2Value": "Tag2Value3",
    "Tag3Value": "Tag3Value3"
  }
]