1
votes

I am relatively new to DataWeave, and was wondering how/if I can transform a message like below using DataWeave instead of a Java transformer.

If I have the following JSON payload of users, with a group and subgroup:

[{
    "GROUP": "GROUP_A",
    "SUBGROUP": "SUBGROUP A1",
    "USER": "USER 1"
}, {
    "GROUP": "GROUP_B",
    "SUBGROUP": "SUBGROUP B1",
    "USER": "USER 1"
}, {
    "GROUP": "GROUP_B",
    "SUBGROUP": "SUBGROUP B1",
    "USER": "USER 2"
}, {
    "GROUP": "GROUP_B",
    "SUBGROUP": "SUBGROUP B2",
    "USER": "USER 3"
}, {
    "GROUP": "GROUP_B",
    "SUBGROUP": "SUBGROUP B2",
    "USER": "USER 4"
}, {
    "GROUP": "GROUP_B",
    "SUBGROUP": "SUBGROUP B2",
    "USER": "USER 5"
}]

What would a DataWeave transformation look like to tranform the payload to something structured like the following:

[   
    {
        "GROUP": "GROUP_A",
        "SUBGROUPS": [{
            "NAME": "SUBGROUP A1",
            "USERS": ["USER 1"]
        }]
    }, {
        "GROUP": "GROUP_B",
        "SUBGROUPS": [{
            "NAME": "SUBGROUP B1",
            "USERS": ["USER 1", "USER 2"]
        }, {
            "NAME": "SUBGROUP B2",
            "USERS": ["USER 3", "USER 4", "USER 5"]
        }]
    }

]

Thanks for any help!

1

1 Answers

4
votes

For DataWeave development, please refer to DataWeave Reference Documentation. At this case You can refer to section Group by …. To transform above message, then try this script:

%dw 1.0
%output application/json
---
payload groupBy $.GROUP pluck {
    GROUP: $$,
    SUBGROUPS: $ groupBy $.SUBGROUP pluck {
        NAME: $$,
        USERS: $.USER
    }
}