首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建JSON Gist (冲突)

创建JSON Gist (冲突)
EN

Stack Overflow用户
提问于 2017-02-24 15:38:15
回答 1查看 354关注 0票数 2

我想使用curl命令创建一个包含JSON的Gist (我检查了一个有效的JSON),如这里所描述的那样。

我首先尝试了这个脚本:

代码语言:javascript
复制
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,所以我尝试直接在命令中传递文件:

代码语言:javascript
复制
curl -H "Content-Type:application/json" -data-binary @jsonFile.json https://api.github.com/gists

但我也犯了同样的错误。我知道,这肯定是POST请求的JSON主体与我文件的JSON (引号、括号.)之间的冲突。

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-24 17:02:46

对于脚本中的问题:

  • 在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请求,但这个示例不会在输入中保留新行:

代码语言:javascript
复制
#!/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

下面将保留更换新线路\\n输入的json中的新行:

代码语言:javascript
复制
#!/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范围。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42442602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档