带选项-d issue

时间:2017-12-04 21:48:08

标签: bash curl

尝试通过API调用(curl)发送一些数据但是遇到curl命令格式的问题:

serviceMsg="$(cat /tmp/response_time)"
perfData=$(/bin/echo "${serviceMsg}" | /bin/sed 's/,//g')

        StatusCode=0

curl -k -s -v -u user:password -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result?service=ExternalURL!ResponseTime' -d "{ \"exit_status\": $StatusCode, \"plugin_output\": \"${perfData}\", \"performance_data\": [ ${perfData} ]}" 

以下是我遇到的错误:

* Connection #0 to host localhost left intact
{
    "error": 400.0,
    "status": "Invalid request body: Error: lexical error: invalid character inside string.\n                                        { \"exit_status\": 0, \"plugin_ou\n                     (right here) ------^\n\n"
}

我缺少什么?

1 个答案:

答案 0 :(得分:0)

不要手工编写JSON代码:使用jq为您生成代码:

perfData=$(sed 's/,//g' /tmp/response_time)

json=$(jq -n --arg sc "$StatusCode" --arg pd "$perfData" \
        '{exit_status: $sc, plugin_output: $pd, performance_data: [ $pd ]}')

url='https://localhost:5665/v1/actions/process-check-result?service=ExternalURL!ResponseTime'

curl -ksv -u user:password -H 'Accept: application/json' -X POST -d "$json" "$url"