我对Mule ESB 3.8.4中的DataWeave具有以下要求,其中shipDate_n
,shipMethod_n
和trackingNumber_n
将在以下情况下从1变为n 输入有效载荷。我需要根据密钥中下划线后的数字对数据进行分组:
输入有效载荷:
[{
"shipDate_1": "2010-01-11T07:00:00Z",
"shipDate_2": "2010-02-11T07:00:00Z",
"shipDate_3": "2010-03-11T07:00:00Z",
"shipMethod_1": "UPS1 Ground",
"shipMethod_2": "UPS2 Ground",
"shipMethod_3": "UPS3 Ground",
"trackingNumber_1": "1",
"trackingNumber_2": "2",
"trackingNumber_3": "3"
}]
必需的输出:
[{
"trackingInfo": [{
"trackingNbr": "1",
"shipMethod": "UPS1 Ground",
"shipDate": "2010-01-11T07:00:00Z"
},
{
"trackingNbr": "2",
"shipMethod": "UPS2 Ground",
"shipDate": "2010-02-11T07:00:00Z"
},
{
"trackingNbr": "3",
"shipMethod": "UPS3 Ground",
"shipDate": "2010-03-11T07:00:00Z"
}
]
}]
答案 0 :(得分:0)
您可以使用pluck方法对n
这样的字段数进行计数,然后迭代n/3
次并动态地形成键以从输入中获取数据。以下代码适用于给定的输入
代码
%dw 1.0
%output application/json
%var data = payload[0]
%var dataSet = (sizeOf (data pluck $$ )) / 3
%var startIndex = 1
---
[trackingInfo : [ startIndex[0] .. dataSet] map {
"trackingNbr": data[("trackingNumber_" ++ $)],
"shipMethod":data[("shipMethod_" ++ $)],
"shipDate": data[("shipDate_" ++ $)]
}]
输入-
[
{
"shipDate_1": "2010-01-11T07:00:00Z",
"shipDate_2": "2010-02-11T07:00:00Z",
"shipMethod_1": "UPS1 Ground",
"shipMethod_2": "UPS2 Ground",
"trackingNumber_1": "1",
"trackingNumber_2": "2"
}
]
输出-
[
{
"trackingInfo": [
{
"trackingNbr": "1",
"shipMethod": "UPS1 Ground",
"shipDate": "2010-01-11T07:00:00Z"
},
{
"trackingNbr": "2",
"shipMethod": "UPS2 Ground",
"shipDate": "2010-02-11T07:00:00Z"
}
]
}
]
另一种方法是基于输入中存在的trackingNumber
个字段的计数
%dw 1.0
%output application/json
%var data = payload[0]
%var dataSet = sizeOf ((data pluck $$ ) filter ($ contains "trackingNumber"))
%var startIndex = 1
---
[trackingInfo : [startIndex[0] .. dataSet] map {
"trackingNbr": data[("trackingNumber_" ++ $)],
"shipMethod":data[("shipMethod_" ++ $)],
"shipDate": data[("shipDate_" ++ $)]
}]
HTH