2016-10-22 4 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"' 
     } 
    }' 

을 반환 "이메일": "값": (유효하지 않음) 및 "전화 번호": "가치":(무효)

+0

내가 강하게 JSON을 생성하는'jq' 같은 것을 사용하는 것이 좋습니다. 그러면 JSON으로 올바르게 인코딩됩니다. 'jq ... | 컬 ... -d @ - ...'. – chepner

답변

1

예에서 은 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''John "'이 단순히'John'이되는 것과 같은 이유로 (인용문 제거라고 불린다). 쉘 스크립팅을 더 할 계획이라면 http://mywiki.wooledge.org/BashGuide와 http://mywiki.wooledge.org/BashFAQ를 읽어 보는 것이 좋습니다. – Leon