簡體   English   中英

如何使用 jq 過濾數組和切片結果

[英]how to filter array and slice results with jq

假設我有以下數據:

{
   "dashboards": [
     {
       "name": "first",
       "type": "standard"
     },
     {
       "name": "second",
       "type": "custom"
     }
   ]
}

(實際上還有更多的數據,我只是展示數據的結構是什么)

我想要做的是獲取standard類型的前 10 個儀表板。

我知道我可以使用以下命令獲取所有standard儀表板: jq '.dashboards[] | select(.type == "standard")' jq '.dashboards[] | select(.type == "standard")'

但我不知道如何對結果數組進行切片......

如果你想要一個數組的結果,你可以使用map

.dashboards | map(select(.type=="standard")) | .[0:10]

然而,這是低效的。 為了效率,最好使用下面討論的limit

如果您希望項目作為流,您可以編寫:

limit(10; .dashboards[] | select(.type=="standard"))

如果您希望將結果作為數組,只需將上述 jq 表達式括在方括號中即可。

這是使用基於步行路徑的unix實用程序jtc的替代方法:

-我冒昧地用另外4個"type": "standard"記錄擴展了源JSON示例,但僅顯示了前3個(出於演示目的):

bash $ <file.json jtc -r
{ "dashboards": [ { "name": "first", "type": "standard" }, { "name": "second", "type": "custom" }, { "name": "second", "type": "standard" }, { "name": "third", "type": "standard" }, { "name": "fifth", "type": "standard" } ] }
bash $ 
bash $ 
bash $ <file.json jtc -w'[type]:<standard>:3 [-1]'
{
   "name": "first",
   "type": "standard"
}
{
   "name": "second",
   "type": "standard"
}
{
   "name": "third",
   "type": "standard"
}
bash $ 

PS>披露:我是jtc工具的創建者

暫無
暫無

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

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