Reputation: 307
I need to loop through an array (of AWS instance Ids'), then pull tags out and add them into an array using jq.
I have variables defining my needs. In this case:
VolumeId
Tag1Value
Tag2Value
Tag3Value
They change as I iterate through in a for loop. I know how to create a new array:
jq -n --arg v "$VolumeId" '[{"VolumeId": $v}]'
However this creates a new JSON array every time. I need it created once, and then append to it as I progress through the loop.
The output I am looking for is a newly create JSON array:
[
{
"VolumeId": $VolumeId,
"Tag1": $Tag1Value,
"Tag2": $Tag2Value,
"Tag3": $Tag3Value
},
{
"VolumeId": $VolumeId,
"Tag1": $Tag1Value,
"Tag2": $Tag2Value,
"Tag3": $Tag3Value
},
{
"VolumeId": $VolumeId,
"Tag1": $Tag1Value,
"Tag2": $Tag2Value,
"Tag3": $Tag3Value
}
]
Any help is really appreciated.
Upvotes: 0
Views: 1655
Reputation: 116967
Here is an example showing how a stream of values (here, a stream of arrays) can be combined into a JSON array of objects:
(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] }) '
Output:
[
{
"VolumeId": "VolumeId1",
"Tag1Value": "Tag1Value1",
"Tag2Value": "Tag2Value1",
"Tag3Value": "Tag3Value1"
},
{
"VolumeId": "VolumeId2",
"Tag1Value": "Tag1Value2",
"Tag2Value": "Tag2Value2",
"Tag3Value": "Tag3Value2"
},
{
"VolumeId": "VolumeId3",
"Tag1Value": "Tag1Value3",
"Tag2Value": "Tag2Value3",
"Tag3Value": "Tag3Value3"
}
]
Upvotes: 2