I am trying to do a curl
call in my shell script where i want to pass the result of sql
in data.
Please assume I have result stored in array as liveCalculators
curl_response=`curl -k -X POST "https://myapiurl" -H "accept: */*" -H "Content-Type: application/json" -d "{ \"keys\": [], \"calcs\": ${liveCalculators[@]}}" -w ";%{http_code}"`
I get Bad Request
as error
Please suggest what can be done to fix it.
CodePudding user response:
Your array output is not encapsulated as a valid JSON, so how about this:
curl_response=$(curl -k -X POST "https://myapiurl" -H "accept: */*" -H "Content-Type: application/json" -d "{ \"keys\": [], \"calcs\": \"${liveCalculators[@]}\" }" -w ";%{http_code}")
In addition, the output of the array liveCalculators
is a BASH list, and you might need to do some parsing and search/replace, to convert it to a valid JSON list..
CodePudding user response:
If you have jq
installed, try this :
curl_response="$(curl -k -X POST "https://myapiurl"\
-H "accept: */*"\
-H "Content-Type: application/json"\
-w ";%{http_code}"\
-d "$(jq -cn '{"keys": [], "calcs": $ARGS.positional}' --args "${liveCalculators[@]}")"
)"
CodePudding user response:
Like this :
myFlatArr=$(
echo "${liveCalculators[@]}" |
perl -lnE 'print join ", ", map { "\042$_\042" } split / /'
)
curl -k -X POST "https://myapiurl" \
-H "accept: */*" \
-H "Content-Type: application/json" \
-w ";%{http_code}" \
-d "@/dev/stdin" <<EOF
{ "keys": [], "calcs": [ $myFlatArr ] }
EOF