Search code examples
integrationdataweavemulesoftmule4anypoint-studio

How to transform a DB payload to JSON array in mulesoft?


attached my input payload for referencemy expected output is [

{ "ID": 1, "code": "IND5321", "DepartureDate": "2/10/2023", "Origin": "CHN", "Destination": "KNR", "availableSeats": 30 }, { "ID": 2, "code": "IND6453", "DepartureDate": "4/10/2023", "Origin": "CHN", "Destination": "AMN", "availableSeats": 60 }, { "ID": 3, "code":"IND5987", "DepartureDate": "3/10/2023", "Origin": "CHN", "Destination": "TVM", "availableSeats": 47 } ]

but my actual output is:

{ "ID": [ 1, 2, 3 ], "code": [ "IND5321", "IND6453", "IND5987" ], "departureDate": [ "2/11/2023", "4/11/2023", "3/11/2023" ], "origin": [ "CHN", "CHN", "CHN" ], "destination": [ "KNR", "AMN", "TVM" ], "availableSeats": [ "30", "60", "47" ] }

How can I transform the database payload to JSON array?


Solution

  • Based on your actual output I'm assuming that the input is an array of similar information to the output but you want to transform some data. You can use the map() function to transform each item in the array.

    Example:

    %dw 2.0
    output application/json
    ---
    payload map {
        ID: $.ID,
        code: $.CODE,
        DepartureDate: $.DEPARTUREDATE
        // other mappings...
    }
    

    What you are doing is probably something like payload.ID for each key which returns an array of all the IDs in the input array.