簡體   English   中英

bash腳本的JSON編碼問題

[英]JSON encoding problems with bash scripting

我正在嘗試創建一個腳本來自動在GitHub上發布問題,但是JSON編碼存在問題。 我想使用文件的內容作為問題的內容。 相關文件有多行和一些特殊字符。 當我運行以下腳本時,它會在GitHub上成功創建問題,但問題的主體似乎混亂了。 文件的所有行最終都被連接在一起,並且特殊字符無法正確顯示。

有沒有辦法解決這個問題? 下面是我的代碼,謝謝!

FILES=*

for f in $FILES; do
    if [ $f == "script" ]; then 
        continue;
    fi

    body=$(cat $f)
    echo "{\"title\": \"title\", \"body\": \"$body\"}" > body.temp
    curl -i -H "Content-Type: application/json" -u "$1:$2" -d @body.temp -X POST https://api.github.com/repos/$f/testing/issues
    rm -rf body.temp
done

如果查看JSON規范 ,您將看到一個字符串可以包含"\\和控制字符 (未轉義) 之外的任何Unicode字符

我不能特別評論github的JSON解析器,但是您幾乎可以肯定希望轉義文件內容。 這是在循環主體中使用Perl單線執行轉義的方法:

body=$(perl -ne 'chomp; s/\\/\\\\/; s/"/\\"/g; print $_ ."\\n"' $f)
echo "{\"title\": \"title\", \"body\": \"$body\"}" > body.temp

測試它:

$ cat >somefile
a
"b"
\c
$ body=$(perl -ne 'chomp; s/\\/\\\\/; s/"/\\"/g; print $_ ."\\n"' somefile)
$ echo "{\"title\": \"title\", \"body\": \"$body\"}" > body.temp
$ cat body.temp
{"title": "title", "body": "a\n\"b\"\n\\c\n"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM