0

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 }

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1
echo "${conf}" | jq -car '.[] | "configy=" + tojson'

produces:

configy={"fraudThreshold":4,"fraudTTLSec":60}
configy={"fraudThreshold":44,"fraudTTLSec":60}

Comments

0
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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.