Search code examples
mulemule-studioanypoint-studiodataweave

Merge two JSON outputs into one with Dataweave


I currently have two JSON files with data.

The first has a list of actions by a user. However, the userID is a UID string instead of their user name.

The second is a JSON list of UID strings with their corresponding user names. I stored this JSON in a Flow Variable named UserPayload

I'd like to merge the user name into the first list so that my output has actual users names instead of the UID.

Here is what I had so far...but the userId part doesn't work since my flowVar is an list. UserPayload FlowVar

%dw 1.0
%output application/csv
---
payload map ((payload01, indexOfPayload01) -> {
     user: payload.01.userId,
     actions: payload01.action,
     FileName: payload01.payload.properties.name default "N/A",
     userId: flowVars.UserPayload.objectName
})

Any help would be appreciated. Thanks!


Solution

  • you can access the right object from the UserPayload flowVar by either filtering the content of UserPayload based on userId or creating a associative array from UserPayload.

    filtering UserPayload

    %dw 1.0
    %output application/json
    ---
    payload map (action, index) -> {
        user: action.user,
        action: action.action,
        FileName: action.FileName,
        userId: (flowVars.UserPayload filter $.objectId == action.user)[0].objectName
    }
    

    associative array

    %dw 1.0
    %output application/json
    %var users = flowVars.UserPayload groupBy $.objectId
    ---
    payload map (action, index) -> {
        user: action.user,
        action: action.action,
        FileName: action.FileName,
        userId: users[action.user][0].objectName
    }
    

    for my examples i used following sample data derived from your question.

    flowVars.UserPayload

    [{
        "objectId": "0000-0000-0001",
        "objectName": "first user"
    }, {
        "objectId": "0000-0000-0002",
        "objectName": "second user"
    }]
    

    payload

    [{
        "user": "0000-0000-0001",
        "action": "some crazy action",
        "FileName": "some-crazy-action.mov"
    }]