如何在bash脚本中使用curl来发布JSON变量?
我通过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时失效。
如果我将上述消息更改为诸如“测试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": "'$2'", "text": "'$message_body'", "to": [ { "email": "'$1'", "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": "'$2'", "text": "'$message_body'", "to": [ { "email": "'$1'", "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 "$2")"
"$(escape_quotes "$message_body")"
"$(escape_quotes "$1")"
)
链接地址: http://www.djcxy.com/p/48573.html
上一篇: How to escape a JSON variable posted with curl in bash script?