创建JSON Gist(冲突)

时间:2017-02-24 15:38:15

标签: json bash curl github-api gist

我想用here创建一个包含JSON(有效的,我检查过)的Gist,其中包含curl命令。

我首先尝试了这个脚本:

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之间的冲突(引号,括号......)。

如何向Gist发送干净的JSON文件?

1 个答案:

答案 0 :(得分:2)

对于脚本中的问题:

    在您的curl请求中
  • ,您在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解析器/构建器构建您的gist请求,而不是此示例将保留输入中的新行:

#!/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\\n保留json输入中的新行:

#!/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范围

相关问题