需求:生成可将指定输入JSON转换为目标输出的JOLT规格
JOLT转换规格实现方案
输入示例
{ "extraPersonCharge": 50, "inventoryTypes": { "KDXN": [ { "name": "Standard Room", "price": 100 }, { "name": "Deluxe Room", "price": 150 } ], "KLON": [ { "name": "Single Bed", "price": 80 } ] } }
期望输出示例
{ "inventoryTypes": { "codes": [ { "code": "KDXN", "name": "Standard Room", "price": 100 }, { "code": "KDXN", "name": "Deluxe Room", "price": 150 }, { "code": "KLON", "name": "Single Bed", "price": 80 } ] } }
JOLT转换规格
[ { "operation": "shift", "spec": { "inventoryTypes": { "*": { "*": { "@": "&3.codes[]", "$2": "&3.codes[&1].code" } } } } } ]
规格说明
- 移除
extraPersonCharge字段:通过shift操作中不指定该字段的映射规则,自动忽略该字段 - 动态生成
codes数组:inventoryTypes.*匹配原结构中inventoryTypes下的所有动态键(如KDXN、KLON)- 内层
*遍历每个键对应的数组元素 @将当前数组元素的所有属性映射到inventoryTypes.codes数组中$2引用上层动态键的值,作为当前元素的code字段,&3确保路径回到inventoryTypes,&1对应数组元素的索引,保证每个元素匹配正确的code值
内容的提问来源于stack exchange,提问作者Optimizer
相关产品推荐
相关产品推荐

