My question is similar to this question but I need something more to be done and can't quite figure out how to do.
This is my JSON string
{
"value": "1"
}
{
"value": "3"
}
{
"value": "4"
}
I need to write a script in BASH to output
In the above example, 2 is missing from the json array. And the script should return 2. If 2 is present in the array it should return 5.
I think I may be able to write the logic to increment the number using a while loop in bash, but I am stuck at this point where I can't figure out how to convert this JSON string to bash array with just the value.
Below is the exact command that I used to get the JSON output. This is AWS CLI command to get all the instances from AWS that has a specific TAG.
readarray -t arr < <(aws ec2 describe-instances --region=us-east-1 --filters --filters "Name=tag:NodeType,Values=worker" --query "Reservations[].Instances[].Tags[]" | jq -r '.[] | select(.Key == "NodeNumber") | {value: .Value}')
printf '%s\n' "${arr[@]}"
The above returns me
{
"value": "1"
}
{
"value": "3"
}
{
"value": "4"
}
However, I need to get just the VALUE field "value" as a bash array
To convert your JSON to a bash array, with help of jq:
$ readarray -t arr < <(jq '.value' file)
$ printf '%s\n' "${arr[@]}"
"1"
"3"
"4"
To fix your expanded example (the exact command), just don't use object construction {value: .Value}, but instead only .Value:
$ readarray -t arr < <(aws ec2 describe-instances --region=us-east-1 --filters --filters "Name=tag:NodeType,Values=worker" --query "Reservations[].Instances[].Tags[]" | jq -r '.[] | select(.Key == "NodeNumber") | .Value')
$ printf '%s\n' "${arr[@]}"
1
3
4
Notice the lack of double quotes, since the -r option now prints only raw string values, not raw JSON Objects.
After you get arr populated with values like this, you can easily iterate over it and perform tests, just as you described in your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With