"Unexpected end of JSON input" 尝试执行 curl POST 命令时出错

"Unexpected end of JSON input" error when trying to do curl POST command

我在使用 curl -X POST 命令发送正确的 json 数据时遇到问题。通过复制和粘贴硬编码值,我已经在我的 mac 本地成功 运行 POST 命令,但我现在正在尝试创建一个 .sh 脚本来自动执行此过程。在 运行 宁下面的代码我得到这个错误:

{"message":"Unexpected end of JSON input"}

这是来自 JSON_STRING 的输出 json,名称为通用名称,其他未更改:

{ "url": "api_url", "tileset": "username.filename" }

一旦我弄清楚如何正确格式化 POST 命令中的 json 我就知道它会起作用,但我似乎无法获得正确的语法。希望一组fresh/experience bash 的眼睛能够发现我的错误:)。此外,我拥有的所有变量都是正确的,并且已经在 mac 终端中由 运行ning 变量值确认。在此先感谢您的帮助!

    curl_url="http://${bucket}.s3.amazonaws.com/${key}"
    echo $curl_url

    tileset_id="username.filename"

    JSON_STRING=$(jq -n \
                  --arg bn "$curl_url" \
                  --arg on "$tileset_id" \
                  '{url: $bn, tileset: $on}')

    echo $JSON_STRING

    curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d $JSON_STRING 'apiurl'

绝对需要引用 shell 变量:

curl ... -d "$JSON_STRING" http://example.com/end/point

否则,shell 将进行分词,-d 的参数变为 {"url":


作为旁注,bash 数组有助于提高可读性:

curl_url="http://${bucket}.s3.amazonaws.com/${key}"
tileset_id="username.filename"

JSON_STRING=$(
    jq -n \
          --arg bn "$curl_url" \
          --arg on "$tileset_id" \
          '{url: $bn, tileset: $on}'
)

curl_opts=(
    -X POST
    -H "Content-Type: application/json" 
    -H "Cache-Control: no-cache" 
    -d "$JSON_STRING"
)

curl "${curl_opts[@]}" 'apiurl'