Reputation: 813
I have a JSON array conf=
[ { "fraudThreshold": 4, "fraudTTLSec": 60 }, { "fraudThreshold": 44, "fraudTTLSec": 60 } ]
I want to loop through its items. So I have done the following:
for configy in $(echo "${conf}" | jq -r ".[]"); do
echo configy=$configy
done
The results are:-
configy={
configy="fraudThreshold":
configy=4,
configy="fraudTTLSec":
and so on.
It is splitting the string using spaces and giving the results one by one. Why is bash showing this weird behavior? Is there any solution to this?
Also, it is giving proper values when I do :
configy=$(echo $conf | jq .[-1])
echo configy=$configy
Result:
configy={ "fraudThreshold": 44, "fraudTTLSec": 60 }
Upvotes: 0
Views: 1156
Reputation: 1391
echo "${conf}" | jq -car '.[] | "configy=" + tojson'
produces:
configy={"fraudThreshold":4,"fraudTTLSec":60}
configy={"fraudThreshold":44,"fraudTTLSec":60}
Upvotes: 1
Reputation: 19375
for configy in $(echo "${conf}" | jq -r ".[]"); do
It is splitting the string using spaces and giving the results one by one. Why is bash showing this weird behavior?
This behavior is not weird at all. See the Bash Reference Manual: Word Splitting:
The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting.
Is there any solution to this?
Mâtt Frëëman and peak presented working solutions; you can slightly optimize them by replacing echo "${conf}" |
with <<<"$conf"
.
Upvotes: 0
Reputation: 116650
In order to loop through the items in the JSON array using bash, you could write:
echo "${conf}" | jq -cr ".[]" |
while read -r configy
do
echo configy="$configy"
done
This yields:
configy={"fraudThreshold":4,"fraudTTLSec":60}
configy={"fraudThreshold":44,"fraudTTLSec":60}
However there is almost surely a better way to achieve your ultimate goal.
Upvotes: 5