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

使用Jolt修改JSON数组对象:存在则更新,不存在则新增

Jolt实现:数组对象的修改/新增逻辑

需求

处理textArray数组:

  • 若存在name="attribute3"的对象,替换其value为自定义传入值
  • 若不存在,新增该对象,value使用自定义传入值
  • 对象位置可在数组任意处(无需固定在末尾)

输入示例

无attribute3的输入

{
  "textArray": [
    {"name": "attribute1", "value": "val1"},
    {"name": "attribute2", "value": "val2"}
  ],
  "customAttr3Value": "new_attr3_val"
}

已有attribute3的输入

{
  "textArray": [
    {"name": "attribute1", "value": "val1"},
    {"name": "attribute3", "value": "old_attr3_val"},
    {"name": "attribute2", "value": "val2"}
  ],
  "customAttr3Value": "updated_attr3_val"
}

预期输出

无attribute3时的输出

{
  "textArray": [
    {"name": "attribute1", "value": "val1"},
    {"name": "attribute2", "value": "val2"},
    {"name": "attribute3", "value": "new_attr3_val"}
  ]
}

已有attribute3时的输出

{
  "textArray": [
    {"name": "attribute1", "value": "val1"},
    {"name": "attribute3", "value": "updated_attr3_val"},
    {"name": "attribute2", "value": "val2"}
  ]
}

问题分析

你之前“先移除再新增”的思路问题在于:移除后新增的对象只能固定在数组末尾,而且会丢失原对象在数组中的位置;另外如果规则逻辑没处理好,容易出现元素丢失或者重复的情况。

正确Jolt规则

下面的规则通过拆分元素、合并对象、重组数组三步实现需求,既能保留原对象位置(可选排序),又能精准修改/新增:

[
  // 第一步:拆分数组元素,分离出attribute3和其他元素
  {
    "operation": "shift",
    "spec": {
      "textArray": {
        "*": {
          "name": {
            "attribute3": {
              "@(2)": "existingAttr3" // 缓存原attribute3对象
            },
            "*": {
              "@(2)": "otherElements[]" // 保留其他所有元素
            }
          }
        }
      },
      "customAttr3Value": "customVal" // 保留自定义值
    }
  },
  // 第二步:构造新的attribute3对象,合并原对象(若存在)的属性,替换value
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "targetAttr3": {
        "name": "attribute3",
        "value": "${customVal}"
      },
      "finalAttr3": ["=merge(@(1,existingAttr3),@(1,targetAttr3))"]
    }
  },
  // 第三步:重组数组,把其他元素和处理后的attribute3合并
  {
    "operation": "shift",
    "spec": {
      "otherElements": {
        "*": "textArray[]"
      },
      "finalAttr3": "textArray[]"
    }
  },
  // 可选:如果需要保持原数组的元素顺序(比如原attribute3的位置),可以加排序规则
  // 这里按name排序,你可以根据实际需求调整排序字段或移除该操作
  {
    "operation": "sort",
    "spec": {
      "textArray": {
        "*": {
          "name": "asc"
        }
      }
    }
  }
]

规则说明

  1. Shift拆分:把数组里的attribute3单独存起来,其他元素放到otherElements数组,同时保留自定义的value值。
  2. Modify合并:先构造一个带有自定义value的attribute3对象,再用merge函数把原对象(如果存在)和新对象合并,这样原对象的其他属性(如果有的话)会被保留,只有value被替换。
  3. Shift重组:把otherElements和处理好的finalAttr3重新组合成新的textArray。
  4. Sort排序:可选操作,如果需要让数组保持特定顺序(比如原顺序或按name排序)就加上,不需要的话直接删掉这一步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 02:52:44