2016-10-22 141 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