SDE
SDE

Reputation: 85

Groupby key segment in Dataweave 1.0

I have the following requirement for DataWeave in Mule ESB 3.8.4 wherein the shipDate_n, shipMethod_n, and trackingNumber_n will vary from 1 to n in the input payload. I need to group the data according to the number after the underscores in the key:

Input payload:

[{
    "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"
}]

Required output:

[{
    "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"
        }
    ]
}]

Upvotes: 0

Views: 449

Answers (1)

AnupamBhusari
AnupamBhusari

Reputation: 2415

You can use pluck method to count number of fields say n and then iterate for n/3 times and form keys dynamically for getting data from input. Following code worked for given input

Code

%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_" ++ $)]
}]

Input-

[
    {
        "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"
    }
]

Output-

[
  {
    "trackingInfo": [
      {
        "trackingNbr": "1",
        "shipMethod": "UPS1 Ground",
        "shipDate": "2010-01-11T07:00:00Z"
      },
      {
        "trackingNbr": "2",
        "shipMethod": "UPS2 Ground",
        "shipDate": "2010-02-11T07:00:00Z"
      }
    ]
  }
]

Another way is based on count of trackingNumber fields present in input

%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

Upvotes: 1

Related Questions