You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jq统计JSON数组元素数量(排除指定元素)

使用jq统计排除指定元素的JSON数组数量

需求说明

用jq工具统计每个对象中snapshots数组的元素数量,需排除其中name字段值为"current"的元素,最终输出每个对象的name对应符合条件的数量。

给定JSON数据

{
  "name": "test1",
  "snapshots": [
    {
      "description": "You are here!",
      "name": "current",
      "digest": "ccc",
      "running": 1
    },
    {
      "description": "You are here!",
      "name": "snap1",
      "digest": "ddd",
      "running": 1
    }
  ]
}
{
  "name": "test2",
  "snapshots": [
    {
      "digest": "bbb",
      "description": "You are here!",
      "name": "current",
      "running": 1
    },
    {
      "description": "You are here!",
      "name": "snap1",
      "digest": "aaa",
      "running": 1
    },
    {
      "description": "You are here!",
      "name": "snap2",
      "digest": "abc",
      "running": 1
    }
  ]
}

期望输出

test1: 1
test2: 2

jq命令实现

执行以下jq命令即可完成需求:

jq -r '.name + ": " + ( [.snapshots[] | select(.name != "current")] | length | tostring )'

命令解释

  • .name: 获取当前对象的name字段值
  • [.snapshots[] | select(.name != "current")]: 过滤snapshots数组,仅保留name不等于"current"的元素并重组为新数组
  • length: 计算过滤后数组的元素数量
  • tostring: 将数字转为字符串,实现和name字段值的拼接
  • -r: 输出原始字符串(而非JSON格式字符串),让结果匹配期望的输出样式

验证结果

将给定的JSON数据作为输入执行上述命令,会直接输出:

test1: 1
test2: 2

内容的提问来源于stack exchange,提问作者secdave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:08:37