在Shell脚本中的cURL POST调用中传递Bash数组

vd2z7a6w  于 2023-01-02  发布在  Shell
关注(0)|答案(3)|浏览(217)

我正在尝试在我的shell脚本中进行curl调用,我想在其中以数据的形式传递sql的结果。

taleResult = `isql -S$envServer -U$USERNAME -h -b << ENDSQL | grep -vE "^Password: $"
$PASSWORD
set nocount on
GO
USE db_cfg
GO
SELECT tablename from MyTable
GO
ENDSQL`

表结果类似于TableA TableB TableC

liveCalculators=()
if echo "$tableResult"; then
            for line in $tableResult
            do
                MessageLog "Table is $line"
                liveCalculators+=(\"$line\")
            done
endif

假设我将结果存储在数组中,格式为liveCalculators

curl_response=` curl_response=`curl -k -X POST "https://myapiurl" \
                -H "accept: */*" \
                -H "Content-Type: application/json" \
                -w ";%{http_code}" \
                -d "@/dev/stdin" <<EOF
                 { "keys": [],, "calcs": ${liveCalculators[@]}}
                EOF`
`

我收到错误请求
请建议可以做些什么来修复它。

hjqgdpho

hjqgdpho1#

数组输出没有封装为有效的JSON,那么下面这个例子怎么样:

curl_response=$(curl -k -X POST "https://myapiurl" -H "accept: */*" -H "Content-Type: application/json" -d "{ \"keys\": [], \"calcs\": \"${liveCalculators[@]}\" }" -w ";%{http_code}")

此外,数组liveCalculators的输出是一个BASH列表,您可能需要进行一些解析和搜索/替换,以将其转换为有效的JSON列表。

2izufjch

2izufjch2#

如果您安装了jq,请尝试以下操作:

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[@]}")"
)"
ifsvaxew

ifsvaxew3#

就像这样:

myFlatArr=$(printf '%s\n' "${liveCalculators[@]}" | paste -sd',')
curl -k -X POST "https://myapiurl" \ 
    -H "accept: */*" \
    -H "Content-Type: application/json" \
    -w ";%{http_code}" \
    -d "@/dev/stdin" <<EOF
{ "keys": [], "calcs": [ $myFlatArr ] }
EOF

相关问题