如何转义在 bash 脚本中使用 curl 发布的 JSON 变量?

How to escape a JSON variable posted with curl in bash script?

我正在通过他们的 API 在 bash 脚本中向 Mandrill 提交消息,'message' 变量的内容导致 API 调用返回错误:

An error occured: {"status":"error","code":-1,"name":"ValidationError","message":"You must specify a key value"}

$message_body变量的内容为:

Trigger: Network traffic high on 'server'
Trigger status: PROBLEM
Trigger severity: Average
Trigger URL:

Item values:

1. Network traffic inbound (server:net.if.in[eth0,bytes]): 3.54 MBytes
2. Network traffic outbound (server:net.if.out[eth0,bytes]): 77.26 KBytes
3. *UNKNOWN* (*UNKNOWN*:*UNKNOWN*): *UNKNOWN*

Original event ID: 84

我不确定字符串的哪一部分将其丢弃,但似乎某些东西导致 JSON 在提交给 Mandrill 的 API.[=16= 时无效]

如果我将上面的消息更改为简单的内容,例如 "Testing 123",消息将成功提交。

执行POST的代码如下:

#!/bin/bash
...
message_body = `cat message.txt`
msg='{ "async": false, "key": "'$key'", "message": { "from_email": "'$from_email'", "from_name": "'$from_name'", "headers": { "Reply-To": "'$reply_to'" }, "auto_html": false, "return_path_domain": null, "subject": "''", "text": "'$message_body'", "to": [ { "email": "''", "type": "to" } ] } }'
results=$(curl -A 'Mandrill-Curl/1.0' -d "$msg" 'https://mandrillapp.com/api/1.0/messages/send.json' -s 2>&1);
echo "$results"

我该怎么做才能确保 $message_body 变量已准备好并准备好作为有效 JSON 提交?

我怀疑问题是你的变量周围缺少引号

msg='{ "async": false, "key": "'$key'", "message": { "from_email": "'$from_email'", "from_name": "'$from_name'", "headers": { "Reply-To": "'$reply_to'" }, "auto_html": false, "return_path_domain": null, "subject": "''", "text": "'$message_body'", "to": [ { "email": "''", "type": "to" } ] } }'
# ..............................^^^^ no quotes around var ...........^^^^^^^^^^^...................^^^^^^^^^^...............................^^^^^^^^^...................................................................^^..............^^^^^^^^^^^^^.........................^^

试试这个:每个变量中的任何双引号都被转义。

escape_quotes() { echo "${1//\"/\\"}"; }
msg=$(
    printf '{ "async": false, "key": "%s", "message": { "from_email": "%s", "from_name": "%s", "headers": { "Reply-To": "%s" }, "auto_html": false, "return_path_domain": null, "subject": "%s", "text": "%s", "to": [ { "email": "%s", "type": "to" } ] } }' \
        "$(escape_quotes "$key")"          \
        "$(escape_quotes "$from_email")"   \
        "$(escape_quotes "$from_name")"    \
        "$(escape_quotes "$reply_to")"     \
        "$(escape_quotes "")"            \
        "$(escape_quotes "$message_body")" \
        "$(escape_quotes "")" 
)