2016-11-05 60 views
0

尋找一些關於我應該參加項目的建議,因爲我對腳本編程很陌生。我的目標如下:Bash腳本項目 - 解析JSON並在循環內構建XML的cURL POST

使用cURL獲取JSON數據,解析特定的對象值。我打算使用jq來解析JSON,然後將結果存儲爲變量。

這裏是我有什麼開始: 樣品JSON -

{ 
    "href": "http://localhost:8080//profiles", 
    "Profiles": [ 
        { 
            "href": "http://localhost:8080/profiles/myprofile", 
            "id": "myprofile", 
            "isRecording": false 
        }, 
        { 
            "href": "http://localhost:8080/profiles/yourprofile", 
            "id": "yourprofile", 
            "isRecording": false 
        } 
    ] 
} 

bash腳本 -

#!/bin/bash 

read -p "Please enter downtime name (and press Enter): " downtimename 
read -p "Please enter timestart:" timeStart 
read -p "Please enter time duration (in minutes): " durationMinutes 

#!/bin/bash 
PROFILE="$(curl --user admin:admin -k -X GET https://xxx.xx.xx.xxx:8080/profiles.json | jq '.Profiles[].id')" 
echo "$PROFILE" 

退貨 - 「我的資料」 「yourprofile」

下一頁我需要構建一個或多個cURL POST xml數據(下面的例子)每個帖子都將是一個單一的xml捲曲文章,對於e在上面的echo「$ PROFILE」中輸入ach行。我在想這將是一個for循環?我正在努力的是如何從「$ PROFILE」中讀取每個值/行,並利用for循環來發布xml,同時在下面的curl URL中替換$ {profile],用於上面的每個結果。

curl -X POST https://xxx.xx.xx.xxx:8080/testprofiles/${profile}/time/${downtimename} --data-urlencode xml="<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<time> 
    <gametime> 
    2016-11-23T05:30:00+02:00 
     <start>${timeStart}</start> 
     <duration unit="MINUTES">${durationMinutes}</duration> 
    </gametime> 
</time>" -H 'Accept: application/xml' \ -H 'Content-Type: application/xml' -u admin:admin 

預先感謝您的幫助

回答

2

字符串和引用

傳遞給--data-urlencode XML字符串沒有雙引號的解釋:

<?xml version=1.0 encoding=UTF-8 standalone=yes?> 
<time> 
    <gametime> 
    2016-11-23T05:30:00+02:00 
     <start>${timeStart}</start> 
     <duration unit=MINUTES>${durationMinutes}</duration> 
    </gametime> 
</time> 

雙引號影響分析的shell語法元素。在命令被調用之前它們被刪除。如果您希望在字符串中使用它的字面值,請將反斜槓加上雙引號,例如"version=\"1.0\""

然而,here documents在大多數情況下都比較方便:

xml=$(cat <<XML 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<time> 
    <gametime> 
    2016-11-23T05:30:00+02:00 
    <start>${timeStart}</start> 
    <duration unit="MINUTES">${durationMinutes}</duration> 
    </gametime> 
</time> 
XML 
) 

jq輸出

使用--raw-output選項跳過JSON格式。 (特別是,默認情況下,字符串值使用雙引號包裝)。

使用--monochrome-output選項關閉顏色輸出。使用此選項,jq將不打印ASCII escape codes

儘管沒有必要,但我建議關閉使用--unbuffered選項的輸出緩衝。使用此選項,jq將在每個JSON對象被打印後刷新輸出緩衝區。

閱讀jq輸出線,由線

你不需要jq命令的輸出存入一個變量。有可能使用pipe

curl --user admin:admin -k -X GET https://xxx.xx.xx.xxx:8080/profiles.json | \ 
    jq --monochrome-output --unbuffered --raw-output \ 
    '.Profiles[].id' | while read profile 
    do 
    echo "Processing profile $profile" 
    url="https://xxx.xx.xx.xxx:8080/testprofiles/${profile}/time/${downtimename}" 
    curl -X POST "$url" \ 
     --data-urlencode "xml=$xml" \ 
     -H 'Accept: application/xml' \ 
     -H 'Content-Type: application/xml' \ 
     -u admin:admin 
    done