【问题标题】:how to filter array and slice results with jq如何使用 jq 过滤数组和切片结果
【发布时间】:2023-04-11 11:15:01
【问题描述】:

假设我有以下数据:

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

(其实数据远不止这些,我只是展示数据的结构是什么)

我要做的是获取standard 类型的前 10 个仪表板。

我知道我可以通过以下方式获得所有standard 仪表板: jq '.dashboards[] | select(.type == "standard")'

但我不知道如何对结果数组进行切片...

【问题讨论】:

  • jq 无法解析您的样本,因为密钥未在双引号中公开
  • 已修复(使用 JavaScript JSON 表示法...)

标签: json select slice jq


【解决方案1】:

如果你想将结果作为一个数组,你可以使用map:

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

但是,这是低效的。为了提高效率,最好使用limit,如下所述。

如果您希望将项目作为流,您可以编写:

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

如果您希望将结果作为一个数组,只需将上面的 jq 表达式括在方括号中即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多