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

如何修改JSON中两个数组的对应位置首个空元素?

问题描述

给定如下JSON结构:

{
  "AlertDestinationAssociations": [
    {
      "SNMPAlertProtocol": null,
      "SecurityName": null
    },
    {
      "SNMPAlertProtocol": "SNMPv3Trap",
      "SecurityName": "oneview_4861333356c624b597366648345"
    },
    {
      "SNMPAlertProtocol": null,
      "SecurityName": null
    },
    {
      "SNMPAlertProtocol": null,
      "SecurityName": null
    },
    {
      "SNMPAlertProtocol": null,
      "SecurityName": null
    },
    {
      "SNMPAlertProtocol": null,
      "SecurityName": null
    },
    {
      "SNMPAlertProtocol": null,
      "SecurityName": null
    },
    {
      "SNMPAlertProtocol": null,
      "SecurityName": null
    }
  ],
  "AlertDestinations": [
    null,
    "1.2.3.4",
    null,
    null,
    null,
    null,
    null,
    null
  ]
}

需求为:修改AlertDestinationAssociations中首个SNMPAlertProtocol和SecurityName均为null的元素,同时修改AlertDestinations数组中对应索引的元素。现有jq语句会批量修改所有空值,需调整为仅修改首个匹配项并联动修改对应数组元素。

解决方案

可通过以下jq命令实现需求:

(.AlertDestinationAssociations | to_entries | map(select(.value.SNMPAlertProtocol == null and .value.SecurityName == null)) | first) as $firstEmpty
| if $firstEmpty then
    .AlertDestinationAssociations[$firstEmpty.key] |= (.SNMPAlertProtocol = "SNMPv3Trap" | .SecurityName = "crap")
    | .AlertDestinations[$firstEmpty.key] = "新的目标地址"
  else
    .
  end

命令说明

  1. 定位首个匹配元素:
    • 将AlertDestinationAssociations转为包含索引(key)和对象(value)的键值对数组
    • 筛选出SNMPAlertProtocol与SecurityName均为null的项,取第一个结果保存为变量$firstEmpty
  2. 联动修改对应内容:
    • 若找到匹配项,修改AlertDestinationAssociations中对应索引的对象,设置指定的协议和安全名称
    • 同时更新AlertDestinations数组中相同索引的元素为目标地址(替换为实际需要的值即可)
  3. 兼容无匹配场景:若未找到符合条件的元素,直接返回原始JSON

执行效果示例

执行命令后,原始JSON的第一个空元素及对应AlertDestinations项会被更新:

{
  "AlertDestinationAssociations": [
    {
      "SNMPAlertProtocol": "SNMPv3Trap",
      "SecurityName": "crap"
    },
    {
      "SNMPAlertProtocol": "SNMPv3Trap",
      "SecurityName": "oneview_4861333356c624b597366648345"
    },
    // 其余元素保持不变
  ],
  "AlertDestinations": [
    "新的目标地址",
    "1.2.3.4",
    // 其余元素保持不变
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:35:12