2016-10-22 140 views
1

我想設置一個基本代碼,將一些客戶插入到我們的客戶支持軟件中,而無需手動進行每一項操作。 當我將變量引入代碼時,我似乎遇到了問題。使用變量的cURL POST請求

此代碼:

#!/bin/sh 
curl https://yoursite.desk.com/api/v2/customers \ 
-u username:password \ 
-X POST \ 
-H "Accept: application/json" \ 
-H "Content-Type: application/json" \ 
-d '{ 
    "first_name":"John", 
    "last_name":"Doe", 
    "phone_numbers": 
     [ 
     { 
      "type":"Other", 
      "value":"5555555555" 
     } 
     ], 
    "emails": 
     [ 
     { 
      "type": "other", 
      "value":"[email protected] 
     } 
     ], 
    "custom_fields": 
     { 
      "field_a":"12345" 
     } 
    }' 

該代碼始終返回錯誤「無效的JSON」

#!/bin/sh 

first=John 
last=Doe 
phone=5555555555 
phone_type=other 
[email protected] 
email_type=other 
id=12345 

curl https://yoursite.desk.com/api/v2/customers \ 
-u username:password \ 
-X POST \ 
-H "Accept: application/json" \ 
-H "Content-Type: application/json" \ 
-d '{ 
    "first_name":'"$first"', 
    "last_name":'"$last"', 
    "phone_numbers": 
     [ 
     { 
      "type":'"$phone_type"', 
      "value":'"$phone"' 
     } 
     ], 
    "emails": 
     [ 
     { 
      "type":'"$email_type"', 
      "value":'"$email"' 
     } 
     ], 
    "custom_fields": 
     { 
      "field_a":'"$id"' 
     } 
    }' 

對於它的價值,因爲我已經調整了代碼偶爾錯誤代碼會顯示「emails」:「value」:(無效)和「phone_numbers」:「value」:(無效)

+0

我強烈建議使用像'jq'生成JSON。這將確保事情是正確的JSON編碼。 'jq ... |捲曲... -d @ - ...'。 – chepner

回答

1

在你的例子中"$first"擴展爲John(雙引號丟失)。其他擴展也是如此。包括在命令中的單引號部分所需的雙引號(但保留周圍的變量擴展雙引號):

#!/bin/sh 

first=John 
last=Doe 
phone=5555555555 
phone_type=other 
[email protected] 
email_type=other 
id=12345 

curl https://yoursite.desk.com/api/v2/customers \ 
-u username:password \ 
-X POST \ 
-H "Accept: application/json" \ 
-H "Content-Type: application/json" \ 
-d '{ 
    "first_name":"'"$first"'", 
    "last_name":"'"$last"'", 
    "phone_numbers": 
     [ 
     { 
      "type":"'"$phone_type"'", 
      "value":"'"$phone"'" 
     } 
     ], 
    "emails": 
     [ 
     { 
      "type":"'"$email_type"'", 
      "value":"'"$email"'" 
     } 
     ], 
    "custom_fields": 
     { 
      "field_a":"'"$id"'" 
     } 
    }' 
+0

我正在學習這種語言的一些基礎知識,但我還沒有遇到過這個。 –

+0

爲什麼「$ first」擴展爲「John」不應該先用引號將$擴展到John嗎? –

+0

@GradyEla出於同樣的原因,「約翰」變成了簡單的「約翰」(它被稱爲引號刪除)。如果你打算做更多的shell腳本,我建議你閱讀http://mywiki.wooledge.org/BashGuide和http://mywiki.wooledge.org/BashFAQ – Leon