Mule4 DataWeave JSON转换需求:面糊与配料组合生成甜甜圈数据
Mule4 DataWeave JSON转换实现
输入JSON
{ "type": "donut", "weight-unit": "lb", "price-unit": "$/lb", "price": 10.75, "batters": { "batter": [ {"id": "10011", "type": "Original", "weight": 500}, {"id": "10021", "type": "Chocolate", "weight": 200, "price": 11.75}, {"id": "10031", "type": "Blueberry", "weight": 250, "price": 11.75}, {"id": "10041", "type": "Devil's Food", "weight": 150} ] }, "topping": [ {"id": "50011", "type": "None", "price": 0}, {"id": "50021", "type": "Glazed", "price": 45.23}, {"id": "50051", "type": "Sugar", "price": 34.1}, {"id": "50071", "type": "Powdered Sugar", "price": 21.11}, {"id": "50061", "type": "Chocolate with Sprinkles", "price": 34.43}, {"id": "50031", "type": "Chocolate", "price": 87.40}, {"id": "50041", "type": "Maple", "price": 64.11} ] }
期望输出JSON(注:原示例存在重复key问题,已修正为合法JSON结构)
{ "type": "donut", "ChocolateFlavoredGlazedDonut": { "weight": 200, "weightUnit": "kg", "price": 56.98, "priceUnit": "$/kg" }, "ChocolateFlavoredSprinklesDonut": { "weight": 200, "weightUnit": "kg", "price": 46.18, "priceUnit": "$/kg" }, "BlueberryFlavoredSugarDonut": { "weight": 250, "weightUnit": "kg", "price": 45.85, "priceUnit": "$/kg" }, "OriginalGlazedDonut": { "weight": 500, "weightUnit": "kg", "price": 45.23, "priceUnit": "$/kg" }, "OriginalMapleDonut": { "weight": 500, "weightUnit": "kg", "price": 64.11, "priceUnit": "$/kg" }, "OriginalSugarDonut": { "weight": 500, "weightUnit": "kg", "price": 34.1, "priceUnit": "$/kg" } }
转换规则
- 每个面糊(batter)与每个配料(topping)组合生成一个键值对,键名为「面糊名称+Flavored+配料名称(去除空格)+Donut」格式的驼峰命名
- 每个键对应的值结构:
weight:取对应面糊的weight字段值weightUnit:硬编码为"kg"price:面糊的price字段值(无该字段则取0)与配料的price字段值之和priceUnit:硬编码为"$/kg"
DataWeave 2.0 转换代码
%dw 2.0 output application/json --- { type: payload.type, (payload.batters.batter flatMap (batter) -> payload.topping map (topping) -> { ("$(batter.type)Flavored$(topping.type replace /\s+/ with '')Donut"): { weight: batter.weight, weightUnit: "kg", price: (batter.price default 0) + topping.price, priceUnit: "$/kg" } } ) reduce ($$ ++ $) }
代码说明
- 保留原输入的
type字段 - 使用
flatMap遍历所有面糊,再用map遍历每个配料,生成所有组合的键值对 - 通过
reduce将多个对象合并为一个对象,实现所有组合的聚合 - 对配料名称做空格去除处理,确保键名格式符合示例要求
- 用
default 0处理面糊无price字段的情况,避免空值错误
内容的提问来源于stack exchange,提问作者aparajita tiwary
相关产品推荐
相关产品推荐

