[英]Mule4 Dataweave transformation
我需要改造以下 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}
]
}
我要的output是
Output:-
{
"type": "donut",
"ChocolateFlavoredGlazedDonut" : {
"weight": 200,
"unit": "kg",
"price": 56.98,
"unit": "$/kg",
},
"ChocolateFlavoredSprinklesDonut" : {
"weight": 200,
"unit": "kg",
"price": 46.18,
"unit": "$/kg",
},
"BlueberryFlavoredSugarDonut" : {
"weight": 250,
"unit": "kg",
"price": 45.85,
"unit": "$/kg",
},
"OriginalGlazedDonut" : {
"weight": 500,
"unit": "kg",
"price": 45.23,
"unit": "$/kg",
},
"OriginalMapleDonut" : {
"weight": 500,
"unit": "kg",
"price": 64.11,
"unit": "$/kg",
},
"OriginalSugarDonut" : {
"weight": 500,
"unit": "kg",
"price": 34.1,
"unit": "$/kg",
},
}
說明:-
"BatterName + ToppingName": { "weight": 500(batter weight), "unit": "kg"(硬編碼), "price": 34.1(bat price + topping price), "unit": "$/kg “(硬編碼,}
例如,如果 Batter Name 是“Chocolate”,那么巧克力面糊將有 6 個配料,每個面糊依此類推。 所以擊球手總數是 4,澆頭是 8,最后我想要 32 個項目 output
您基本上需要在澆頭和面糊上進行交叉連接。 您可以使用join
from dw::core::Arrays
來執行此操作。 它接受 2 arrays 作為輸入以及兩個連接條件(內聯函數)。 為此,您可以只傳遞始終返回true
的 function(或任何其他 static 值,但它在兩個標准函數中應該相同),因此 function 會將每個項目與每個項目合並,您將獲得所有可能的組合。
我注意到合並后的零食名稱不是很直接,所以我為此單獨創建了一個 function。
%dw 2.0
import join from dw::core::Arrays
import capitalize from dw::core::Strings
output application/json
fun getComboName(batterName, toppingName, snackType) =
capitalize(batterName)
++ (if(lower(batterName) != "original")("Flavoured") else "")
++ (if(lower(toppingName) != "none") capitalize((toppingName splitBy " ")[-1]) else "")
++ capitalize(snackType)
---
join(
payload.batters.batter,
payload.topping,
(a) -> true,
(a) -> true
)
reduce ((combo, acc={"type": payload."type"}) -> {
(acc),
(getComboName(combo.l."type", combo.r."type", payload."type")): {
weight: combo.l.weight,
unit: "kg",
price: (combo.l.price default 0) + (combo.r.price default 0),
unit: "\$/kg"
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.