This is my script.sh:
emails=$(curl -X GET http://0.0.0.0:5000/v1/user/all | jq 'map(.[].email)')
echo $emails
for email in ${emails[@]}
do
echo $email
FROM=$(date "%Y-%m-%d %T")
TO=$(date -d "$today -1 month" " %Y-%m-%d %T")
SEND=true
JSON_STRING='{"email":"'"$email"'","from":"'"$FROM"'","to":"'"$TO"'","send":"'"$SEND"'"}'
curl -X POST http://0.0.0.0:5000/v1/invoice/print -d JSON_STRING
done
The emails data i get from the first API call is the following:
["[email protected]", "[email protected]", "[email protected]"]
the API POST curl does this:
{"email":"[","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
{"email":""[email protected]",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
{"email":""[email protected]",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
{"email":""[email protected]",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
{"email":"]","from":"2022-03-28 09:59:07","to":"2022-02-28 09:59:07","send":"true"}
{"message": "Internal Server Error"}
edit: the scripts echo return:
["[email protected]", "[email protected]", "[email protected]"]
[
{"email":"[","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
"[email protected]",
{"email":""[email protected]",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
"[email protected]",
{"email":""[email protected]",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
"[email protected]",
{"email":""[email protected]",","from":"2022-03-28 09:59:06","to":"2022-02-28 09:59:06","send":"true"}
{"message": "Internal Server Error"}
]
{"email":"]","from":"2022-03-28 09:59:07","to":"2022-02-28 09:59:07","send":"true"}
{"message": "Internal Server Error"}
I don't understand why the emails loop is treating the parentheses [ and ] and returning ' "[email protected]",' instead of just '[email protected]'? What am I doing wrong?
CodePudding user response:
This is the output you're getting from jq
:
[
"[email protected]",
"[email protected]",
"[email protected]",
]
bash-wise, it's not an array, it's a multi-line string.
Indexing it with [@]
changes nothing and returns the whole string. Iterating over it with for var in $multiline_string
executes the code for each space-separated token of the string. Since your emails do not contain spaces, that's for each line of the string.
You need to have jq
produce a space-separated list of email addresses without quotes for bash to process them easily. Just change your jq command into the following :
jq -r 'map(.[].email)[]'