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

JOLT转换中如何将数组索引从0改为1起始

JOLT索引从1开始的解决方案

要实现索引从1而非0开始,需要分三步处理:先保留原索引,再计算1-based索引,最后重新映射键名。以下是完整的JOLT Spec:

[
  {
    "operation": "shift",
    "spec": {
      "positions": "positions",
      "line_items": {
        "*": {
          "@(sku)": "temp[&1].sku",
          "@(quantity)": "temp[&1].quantity"
        }
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "temp": {
        "*": {
          "index": "=int(@(1)) + 1"
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "positions": "positions",
      "temp": {
        "*": {
          "sku": "id@(1,index)",
          "quantity": "quantity@(1,index)"
        }
      }
    }
  }
]

步骤说明:

  • 第一步(shift):将line_items中的每个元素的sku和quantity存入临时数组temp,用&1捕获原数组的0-based索引作为temp的键,同时保留positions字段。
  • 第二步(modify-overwrite-beta):为temp中的每个元素添加index字段,通过=int(@(1)) +1将原0-based索引转换为1-based索引(@(1)指代当前元素在temp中的键,即原索引)。
  • 第三步(shift):将temp中的sku映射为id拼接1-based索引的键名,quantity同理,最终得到目标结构。

示例输出:

{
  "positions" : 2,
  "id1" : "149",
  "quantity1" : 1,
  "id2" : "4270",
  "quantity2" : 1,
  "id3" : "1440",
  "quantity3" : 3
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:23:21