2015-06-03 75 views
0

我提交的消息在通過他們的API和「消息」變量的內容bash腳本來山魈導致API調用一個錯誤回來:如何在bash腳本中使用curl來發布JSON變量?

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時提交山魈的API是無效的。

如果我將上述消息更改爲諸如「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": "'$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?

+2

更改爲'message_body = $(cat message.txt)',或者如果您想讓您的同事驚訝,'m_b = $( shellter

+1

如果你想**絕對肯定** message_body是有效的JSON,請使用特定於JSON的工具(如'jq')來生成它;這將涵蓋所有的角落案例 - 文字引號&c。除非'jq'被告知使用非JSON輸出格式,否則它實際上不能發出無效的JSON內容。 –

回答

3

我懷疑問題是缺乏周圍的變量引用的

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")" 
) 
相關問題