我正在從 NYTimes API 獲取一些 JSON 資料。我可以把東西變成這種形式:
"results": [
{
"headline": "such and such",
"url": "http://such.and.such.com",
...
},
{
"headline": "so and so",
"url": "http://so.and.so.com",
...
},
...
]
我想為陣列中的每個物件回顯 1 個字串,以便字串文本顯示標題,并且該字串可點擊到 url。
我知道我希望如何構建字串:
echo -e "\e]8;;$URL\a$TITLE\e]8;;\a"
我不知道如何使用jq來填充字串的這些可變部分。
> echo $RESULTS | jq '.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"'
jq: error: Invalid escape at line 1, column 4 (while parsing '"\e"') at <top-level>, line 1:
.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"
jq: error: Invalid escape at line 1, column 4 (while parsing '"\a"') at <top-level>, line 1:
.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"
jq: error: Invalid escape at line 1, column 4 (while parsing '"\e"') at <top-level>, line 1:
.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"
jq: error: Invalid escape at line 1, column 4 (while parsing '"\a"') at <top-level>, line 1:
.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"
jq: 4 compile errors
uj5u.com熱心網友回復:
\e并且\a在 JSON 字串中無效;要對轉義字符和鈴聲控制字符進行編碼,您需要分別使用\u001b和\u0007。您可能還希望使用該-r選項jq使其輸出原始字串(而不是 JSON 編碼)。
我還強烈推薦雙引號 shell 變數參考(以避免分詞和通配符擴展的奇怪影響),并使用小寫或混合大小寫的變數名稱以避免與許多具有特殊含義或功能的全大寫名稱沖突.
所以是這樣的:
echo "$results" | jq -r '.results[] | "\u001b]8;;\(.url)\u0007\(.title)\u001b]8;;\u0007"'
或者,在 bash(但不是所有其他 shell)中,您可以使用 here-string 而不是echo:
jq -r '.results[] | "\u001b]8;;\(.url)\u0007\(.title)\u001b]8;;\u0007"' <<<"$results"
uj5u.com熱心網友回復:
您可以使用 bash 轉義序列保留原始 jq 腳本$:
jq -r $'.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"' <<< "$results"
這里 bash 將轉換\e為 character 0x1b。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/477873.html
下一篇:`this`是關鍵字還是文字?
