Devendra
Devendra

Reputation: 221

"Transform JSON to JSON with applying groupBy"

I'm transforming payload from json to json with applying groupBy condition but I am not getting proper data what I want. I have to group the Employee and list his all the tasks. Currently I am able to apply groupBy employee but his all task is not showing.

payload is:

[
    {
        "Id": 1,
        "EmployeeName": "AA",
        "Task": {
            "TaskName": "Deploy"
        }
    },
    {
        "Id": 1,
        "EmployeeName": "AA",
        "Task": {
            "TaskName": "Test"
        }
    },
    {
        "Id": 3,
        "EmployeeName": "BB",
        "Task": {
            "TaskName": "Deploy"
        }
    }
]

This is my transformation code:

%dw 1.0
%output application/json
---
(payload groupBy ($.EmployeeName ++ $.Id)) map {
    EmployeeName : $[0].EmployeeName,
    Email : $[0].Email,
    Task: $[0].Task  
}

This is what I am getting:

[
    {
        "EmployeeName": "AA",
        "Task": {
            "TaskName": "Deploy"
        }
    },
    {
        "EmployeeName": "BB",
        "Task": {
            "TaskName": "Deploy"
        }
    }
]

Expected result:

[
    {
        "EmployeeName": "AA",
        "Task1": {
            "TaskName": "Deploy"
        },
        "Task2": {
            "TaskName": "Test"
        }
    },
    {
        "EmployeeName": "BB",
        "Task1": {
            "TaskName": "Deploy"
        }
    }
]

How can I modify my dataweave to get the expected result.

Upvotes: 0

Views: 54

Answers (1)

AnupamBhusari
AnupamBhusari

Reputation: 2415

Following code should work fine.

%dw 1.0
%output application/json
---
payload groupBy ($.Id ++ $.EmployeeName) map {
    EmployeeName : $[0].EmployeeName,
    ({Task : {($.Task map {
        ('Task' ++ $$ + 1) : $
    })}})
}

Hope this helps.

Upvotes: 2

Related Questions