Mulesoft DataWeave:转换平面列表

时间:2016-02-10 02:11:56

标签: mule mule-studio anypoint-studio dataweave

我对DataWeave比较陌生,并且想知道如何使用DataWeave而不是Java转换器来转换下面的消息。

如果我有以下用户的JSON有效负载,则包含组和子组:

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

DataWeave转换会将有效负载转换为如下结构的内容:

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

]

感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

对于DataWeave开发,请参阅DataWeave Reference Documentation。在这种情况下,您可以参考分组...。要转换上面的消息,请尝试以下脚本:

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