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

如何在jq中结合global标志使用capture返回结果数组

解决jq捕获结果转为数组并转换数字类型的问题

需求说明

输入JSON:

{
  "text": "a1\nb2"
}

期望输出:

[
  {
    "letter": "a",
    "number": 1
  },
  {
    "letter": "b",
    "number": 2
  }
]

问题分析

使用带"g"标志的capture会输出多个独立的JSON文档,而非单个数组结构;同时捕获得到的number字段是字符串类型,需要转为数字类型。

解决方案

将capture的结果用数组包裹,再通过map处理字段类型转换:

$ echo '{
  "text": "a1\\nb2"
}' | jq '[.text | capture("(?<letter>[a-z])(?<number>[0-9])";"g")] | map(.number |= tonumber)'

执行后输出符合预期:

[
  {
    "letter": "a",
    "number": 1
  },
  {
    "letter": "b",
    "number": 2
  }
]

关键步骤解释

  • [.text | capture(...; "g")]:把全局捕获生成的多个独立对象包裹为一个数组,解决多文档输出的问题。
  • map(.number |= tonumber):遍历数组内的每个对象,将number字段的字符串值转换为数字类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:50:50