Issue
I need to execute cat build.json | jq '.Stage*.Name'
for 5 times, where *
is a number from 1 to 5.
I tried this:
for (( c=1; c<5; c++ ))
do
echo $c
cat build.json | jq '.Stage${c}.Name'
done
And I got this error:
jq: error: syntax error, unexpected '$', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.Stage${c}.Name
jq: 1 compile error
How do I do this properly?
Solution
Consider the following json file (./json.json
):
{
"data": {
"stage1": {
"name": 1
},
"stage2": {
"name": 2
},
"stage3": {
"name": 3
},
"stage4": {
"name": 4
},
"stage5": {
"name": 5
}
}
}
With this setup, you can use jq's arg to parse your iterator:
#!/bin/bash
for (( i = 1; i <= 5; i++ )); do
echo "i: $i"
jq --arg i $i '.data.stage'$i'.name' < json.json
done
Producing the following output:
i: 1
1
i: 2
2
i: 3
3
i: 4
4
i: 5
5
passing arguments to jq filter
Answered By - 0stone0 Answer Checked By - David Marino (WPSolving Volunteer)