我正在嘗試使用jq迭代一些分隔的文本檔案,并從行生成物件。
我還想json在生成的結果中添加一些“靜態”物件(下例中的 shell 變數)。
我想出了下面的解決方案,它確實產生了我想要的輸出。但是,因為我對jq不是很自信,所以每次用它解決問題時,感覺就像猴子敲打打字機,而不是精心設計的答案。所以,我在想象這可能是不正確的。
資料.txt
apple|fruit
Tesla|car
sparrow|bird
測驗(bash 外殼):
$ json='[
{ "object": "love", "type": "emotion" },
{ "object": "Ukraine", "type": "country" }
]'
$ jq --slurp --raw-input --argjson extra "$json" '
split("\n") |
map(select(length>0)) |
map(split("|") | {
object: .[0],
type: .[1]
}) as $data |
$data $extra' data.txt
輸出:
[
{
"object": "apple",
"type": "fruit"
},
{
"object": "Tesla",
"type": "car"
},
{
"object": "sparrow",
"type": "bird"
},
{
"object": "love",
"type": "emotion"
},
{
"object": "Ukraine",
"type": "country"
}
]
這有效率嗎?
uj5u.com熱心網友回復:
我不知道它是否更有效,但您可以使用--raw-input或-R不使用--slurp或-s按行讀取原始文本流(無需用換行符拆分)來縮短代碼,/操作員在一行內執行“列”拆分,并reduce從您的“靜態”資料開始逐步建立您的最終結構。
jq -Rn --argjson extra "$json" '
reduce (inputs / "|") as [$object, $type] ($extra; . [{$object, $type}])
' data.txt
如果您希望最后的“靜態”資料,請在之后添加它并從一個空陣列開始:
jq -Rn --argjson extra "$json" '
reduce (inputs / "|") as [$object, $type] ([]; . [{$object, $type}]) $extra
' data.txt
uj5u.com熱心網友回復:
你可以試試這個:
jq -nR --argjson extra "$json" '
[inputs / "|" | {object:.[0], type:.[1]}] $extra' data.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/437371.html
