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

如何在jq中给指定嵌套数组追加元素并返回根对象?

解决jq修改JSON后返回根对象的问题

你的问题出在当前jq命令直接输出了匹配的rules元素,而没有修改并返回整个原始JSON对象。要解决这个问题,你需要使用jq的赋值操作符|=结合map来更新目标数组,同时保留整个根结构。

修改后的命令

config=$(echo "$config" | jq \
--arg out_tag "$outbound_tag" \
--arg in_tag "$inbound_tag" \
'.routing.rules |= map(
    select(.outboundTag == $out_tag) | .inboundTag += [$in_tag]
)')

原理说明

  • .routing.rules |= map(...):|=是jq的赋值操作,它会把map处理后的结果重新赋值回.routing.rules路径,这样整个根对象会被保留并更新。
  • map(select(.outboundTag == $out_tag) | .inboundTag += [$in_tag]):map遍历rules数组中的每一个元素,只对outboundTag匹配$out_tag的元素执行inboundTag数组追加操作,其他元素保持原样。

效果验证

假设你的原始JSON是:

{
  "routing": {
    "rules": [
      {
        "type": "field",
        "inboundTag": ["input"],
        "outboundTag": "vpn-out"
      },
      {
        "type": "field",
        "inboundTag": ["alternate"],
        "outboundTag": "raw-out"
      }
    ]
  }
}

当outbound_tag="vpn-out"且inbound_tag="new-input"时,执行命令后$config会被赋值为修改后的完整JSON:

{
  "routing": {
    "rules": [
      {
        "type": "field",
        "inboundTag": ["input", "new-input"],
        "outboundTag": "vpn-out"
      },
      {
        "type": "field",
        "inboundTag": ["alternate"],
        "outboundTag": "raw-out"
      }
    ]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:42:43