请求生成关联航班与价格引用的JOLT转换规则
JOLT转换:替换JSON引用为实际实体解决方案
问题场景
现有包含flights、prices、solutions节点的JSON数据,其中solutions节点通过price-ref和flights-ref字段关联prices和flights中的对应数据,需要将这些引用替换为实际实体,生成扁平化的目标结构。
示例输入
{ "flights": [ { "id": "FL1", "origin": "NYC", "destination": "LAX", "departure": "2024-05-01T08:00:00" }, { "id": "FL2", "origin": "LAX", "destination": "NYC", "departure": "2024-05-02T10:00:00" } ], "prices": [ { "id": "PR1", "amount": 299.99, "currency": "USD", "tax": 35.00 }, { "id": "PR2", "amount": 349.99, "currency": "USD", "tax": 40.00 } ], "solutions": [ { "id": "SOL1", "price-ref": "PR1", "flights-ref": ["FL1"] }, { "id": "SOL2", "price-ref": "PR2", "flights-ref": ["FL1", "FL2"] } ] }
JOLT转换规则
[ // 构建flights和prices的ID映射表,便于快速匹配引用 { "operation": "shift", "spec": { "flights": { "*": { "id": "flightMap.&", "*": "flightMap.&1.&" } }, "prices": { "*": { "id": "priceMap.&", "*": "priceMap.&1.&" } }, "solutions": "solutions" } }, // 遍历solutions,替换引用为实际实体数据 { "operation": "shift", "spec": { "solutions": { "*": { "id": "output[&1].id", "price-ref": { "@(2,priceMap.&)": "output[&2].price" }, "flights-ref": { "*": { "@(3,flightMap.&)": "output[&3].flights[&1]" } } } } } }, // 清理临时映射表(可选,若无需保留映射可省略) { "operation": "remove", "spec": { "flightMap": "", "priceMap": "", "solutions": "" } } ]
示例输出
{ "output": [ { "id": "SOL1", "price": { "id": "PR1", "amount": 299.99, "currency": "USD", "tax": 35.00 }, "flights": [ { "id": "FL1", "origin": "NYC", "destination": "LAX", "departure": "2024-05-01T08:00:00" } ] }, { "id": "SOL2", "price": { "id": "PR2", "amount": 349.99, "currency": "USD", "tax": 40.00 }, "flights": [ { "id": "FL1", "origin": "NYC", "destination": "LAX", "departure": "2024-05-01T08:00:00" }, { "id": "FL2", "origin": "LAX", "destination": "NYC", "departure": "2024-05-02T10:00:00" } ] } ] }
规则说明
- 第一步
shift:将flights和prices转换为以id为键的映射表,通过&和&1占位符实现键值对的映射,为后续引用匹配提供快速查找路径。 - 第二步
shift:通过相对路径引用(@(n,path)),将solutions中的price-ref和flights-ref替换为映射表中的实际实体数据,其中数字n代表向上遍历的层级数。 - 第三步
remove:清理临时生成的映射表字段,仅保留最终输出结构。
内容的提问来源于stack exchange,提问作者Carlos Tse
相关产品推荐
相关产品推荐

