基于Jolt Transformation实现数组元素比较与筛选需求
调整Jolt转换实现指定规则的cost数组生成
需求规则
现有一个包含5个元素的数组,需对索引1和索引2的元素进行比较,根据是否为整数保留其中一个元素,其余元素保持不变,最终数组保留4个元素,规则如下:
- 若索引1的元素为整数且索引2的元素为空字符串,保留索引1的元素,移除索引2的元素;
- 若索引1的元素为空字符串且索引2的元素为整数,保留索引2的元素,移除索引1的元素;
- 若索引1和索引2的元素均为整数,仅保留索引1的元素,移除索引2的元素。
输入JSON
{ "destination": [ { "destinationName": ["dest1","dest2","dest3"], "taxi_cost": [10,20,30], "van_one_way_cost": [7,6,""], "van_two_way_cost": [14,"",16], "subway_cost": [11,22,33], "bus_cost": [21,22,23] } ] }
当前转换的问题
现有Jolt转换会同时保留van_one_way_cost和van_two_way_cost两个元素到cost数组中,不符合规则要求,需要调整逻辑将二者合并为一个元素。
期望输出
{ "destination": [ { "destName": "dest1", "vanFee": 7 }, { "destName": "dest2", "vanFee": 6 }, { "destName": "dest3", "vanFee": 16 } ], "transportList": { "transportDestination": [ { "name": "dest1", "transports": [ { "cost": [10,7,11,21] } ] }, { "name": "dest2", "transports": [ { "cost": [20,6,22,22] } ] }, { "name": "dest3", "transports": [ { "cost": [30,16,33,23] } ] } ] } }
修正后的Jolt转换
[ { "operation": "shift", "spec": { "destination": { "*": { "destinationName": { "*": { "@": [ "destination.[#2].destName", "transportList.transportDestination.[#2].name" ] } }, "taxi_cost": { "*": { "@": "transportList.transportDestination.[&1].transports.[&1].cost[0]" } }, "van_one_way_cost": { "*": { "@": [ "destination.[#2].owVanFee", "transportList.transportDestination.[&1].vanTemp.oneWay" ] } }, "van_two_way_cost": { "*": { "@": [ "destination.[#2].twVanFee", "transportList.transportDestination.[&1].vanTemp.twoWay" ] } }, "subway_cost": { "*": { "@": "transportList.transportDestination.[&1].transports.[&1].cost[2]" } }, "bus_cost": { "*": { "@": "transportList.transportDestination.[&1].transports.[&1].cost[3]" } } } } } }, { "operation": "modify-overwrite-beta", "spec": { "destination": { "*": { "vanFee": ["=toInteger(@(1,owVanFee))", "=(@(1,twVanFee))"] } }, "transportList": { "transportDestination": { "*": { "vanSelected": [ "=notEmpty(@(1,vanTemp.oneWay))?@(1,vanTemp.oneWay):@(1,vanTemp.twoWay)", "=toInteger(@(1,vanSelected))" ], "transports": { "*": { "cost[1]": "@(2,vanSelected)" } } } } } } }, { "operation": "remove", "spec": { "destination": { "*": { "owVanFee": "", "twVanFee": "" } }, "transportList": { "transportDestination": { "*": { "vanTemp": "", "vanSelected": "" } } } } } ]
关键改动说明
Shift阶段:
- 给
cost数组的各元素指定固定索引:taxi_cost对应索引0,subway_cost对应索引2,bus_cost对应索引3,预留索引1给合并后的van费用。 - 将
van_one_way_cost和van_two_way_cost暂存到vanTemp对象中,方便后续规则判断。
- 给
Modify阶段:
- 用
=notEmpty实现规则判断:优先保留非空的oneWay值,否则使用twoWay值,再转换为整数类型。 - 将选中的van费用赋值到
cost数组的索引1位置。
- 用
Remove阶段:
- 清理临时生成的
vanTemp和vanSelected字段,保证输出结构整洁。
- 清理临时生成的
内容的提问来源于stack exchange,提问作者shobika
相关产品推荐
相关产品推荐

