使用变量的cURL POST请求

时间:2016-10-22 17:33:30

标签: json api curl post sh

我正在尝试设置一个基本代码,将一些客户插入到我们的客户支持软件中,而无需进入并手动执行每个客户。 当我在代码中引入变量时,我似乎遇到了问题。

此代码有效:

#!/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":"johndoe@email.com
        }
      ],
    "custom_fields":
      {
          "field_a":"12345"
      }
    }'

此代码始终返回错误'无效的JSON'

#!/bin/sh

first=John
last=Doe
phone=5555555555
phone_type=other
email=johndoe@email.com
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"'
      }
    }'

为了它的价值,因为我偶尔会调整代码,错误代码会显示"电子邮件":"值" :(无效)和&#34 ; PHONE_NUMBERS":"值" :(无效)

1 个答案:

答案 0 :(得分:1)

在您的示例中,"$first"已扩展为John(双引号丢失)。其他扩展也是如此。在命令的单引号部分中包含所需的双引号(但保留变量扩展周围的双引号):

#!/bin/sh

first=John
last=Doe
phone=5555555555
phone_type=other
email=johndoe@email.com
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"'"
      }
    }'