2017-02-24 59 views
2

我想用curl命令創建一個包含JSON(有效的一個,我選中)的Gist,如here所述。創建JSON要點(衝突)

我第一次嘗試這個腳本:

configText=$(cat jsonFile.json) 

generate_post_data() 
{ 
cat <<EOF 
{ 
    "description": "the description for this gist", 
    "public": true, 
    "files": { 
    "file1.txt": { 
     "content": $configText 
    } 
    } 
} 
EOF 
} 

curlBody="$(generate_post_data)" 

curlResponse=$(curl -H "Content-Type: application/json" -X POST -d '$curlBody' https://api.github.com/gists) 

這給了我錯誤Problems parsing JSON,所以我試圖直接通過該文件中的命令:

curl -H "Content-Type:application/json" -data-binary @jsonFile.json https://api.github.com/gists 

但我得到同樣的錯誤。我知道這必須是POST請求的JSON正文和我的文件的JSON(引號,括號......)之間的衝突。

如何發送乾淨的JSON文件到Gist?

回答

2

對於腳本的問題:

    在嫋嫋的要求
  • ,您在POST -d '$curlBody'使用在你的bash變量單引號,使用雙引號將其展開:POST -d "$curlBody"
  • content是一個文本字段: "content": $configText"content": "$configText"
  • configText可以有新的線路和轉義雙引號"這打破你content JSON數據。你可以使用下面的轉義引號,並刪除新行:

    configText=$(cat test.json | sed 's/\"/\\\"/g' | tr -d '\n') 
    

下面的例子建立與jq JSON解析器/構造你要點的要求,不是說這個例子保留在新的生產線的輸入:

#!/bin/bash 

ACCESS_TOKEN="YOUR_ACCESSS_TOKEN" 

description="the description for this gist" 
filename="file1.txt" 

curlBody=$(jq --arg desc "$description" --arg filename "$filename" '.| 
{ "description": $desc, 
    "public": true, 
    "files": { 
     ($filename) : { 
      "content": tostring 
     } 
    } 
}' jsonFile.json) 

curl -v -H "Content-Type: application/json" \ 
     -H "Authorization: Token $ACCESS_TOKEN" \ 
     -X POST -d "$curlBody" https://api.github.com/gists 

下面將通過replacing new lines保存在您的JSON輸入新線,\\n

#!/bin/bash 

ACCESS_TOKEN="YOUR_ACCESSS_TOKEN" 

description="the description for this gist. There are also some quotes 'here' and \"here\" in that description" 
public="true" 
filename="file1.txt" 

desc=$(echo "$description" | sed 's/"/\\"/g' | sed ':a;N;$!ba;s/\n/\\n/g') 
json=$(cat test.json | sed 's/"/\\"/g' | sed ':a;N;$!ba;s/\n/\\n/g') 

curl -v -H "Content-Type: text/json; charset=utf-8" \ 
     -H "Authorization: Token $ACCESS_TOKEN" \ 
     -X POST https://api.github.com/gists -d @- << EOF 
{ 
    "description": "$desc", 
    "public": "$public", 
    "files": { 
     "$filename" : { 
      "content": "$json" 
     } 
    } 
} 
EOF 

請注意,您的訪問令牌必須有gist範圍

+0

OMG太感謝你了! – ilansas

+0

我更新了我的帖子,其中保留了主要內容中的新行 –