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
相关产品推荐
相关产品推荐

