我正在编写一个试图通过Github的API发送Gist的脚本。所有请求都需要采用以下JSON格式:
{
"description": "the description for this gist",
"public": true,
"files": {
"file1.txt": {
"content": "String file contents"
}
}
}
我对如何完成“内容”字段的格式化感到困惑。我正在尝试在“内容”字段中发送代码的文本文件,例如
if(n <= 3)
n++;
else
n--;
如果我将所有行添加换行符(即“n ++”; - &gt;“n ++; \ n”)并转义其他字符(如反斜杠和引号),那么我可以将文件作为字符串发送,其中JSON看起来像这样:
{
"description": "the description for this gist",
"public": true,
"files": {
"file1.txt": {
"content": "if(n<=3)\nn++;\nelse\nn--;"
}
}
}
,但所有缩进都丢失了,Gist最终看起来像这样:
if(n <= 3)
n++;
else
n--;
如果我将文件作为base64编码的字符串发送,那么我会收到JSON解析错误。我正在将JSON写入文本文件并使用curl发送请求,如下所示
curl --user user -X POST -H 'Content-Type application/json' -d @test.txt https://api.github.com/gists
那么我有什么选择来保存文本文件的内容并保留缩进?我目前正在用bash编写脚本,但是如果有一种语言具有针对这种情况设计的解析功能,我会乐于使用它。
有没有办法发送保存在缩进状态的文件作为此JSON对象的字符串文字?我误解了API吗?
答案 0 :(得分:2)
看看你的字符串:
"content": "if(n<=3)\nn++;\nelse\nn--;"
如果有缩进,你会在字符串中看到它:
"content": "if(n<=3)\n n++;\nelse\n n--;"
由于您编写的代码中存在错误,您的bash脚本会删除缩进。这通常是由于未能引用或使用不正确的while read
循环。你的剧本不包括在内,所以我不能说出来。
使用jq
代替尝试转义自己的数据,可以避免所有这些以及更多错误:
$ cat file
if(n <= 3)
n++;
else
n--;
$ jq -R -s . file
"if(n <= 3)\n n++;\nelse\n n--;\n"
答案 1 :(得分:1)
您可以使用sed将文件转换为内容字符串。
cat <<END
{
"description":"filename",
"public":false,
"files": {
"filename": {
"content":"$(sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/$/\\n/' <filename)"
}
}
}
END
请参阅我的gistpost脚本。非常基本和粗糙,但它的工作原理