Search code examples
mulemule-componentdataweavemule-esb

Create sub array in dataweave 2


I have a json meesage and want to get the below output. Input message:

[
{
 Header:{
id:12,
dept: HR
},
details:[
{ 
 lineid: 1234,
 acc : "ABC"
},
{ 
 lineid: 98745,
 acc : "cba"
}]
}]

expected output:

[
 {
 "id": 12,
 "lineid": 1234},
 {
 "id": 12,
 "lineid": 98745
 }
]

used dataweave:

%dw 2.0
output application/json
---


 payload  map ( payload01 , indexOfPayload01 ) -> {

((payload01.Header map ( payload02, indexOfPayload02 ) -> {
    id: payload01.Header.id,
    lineid: payload02.lineid
} 

) )
} 

My Output looks fine only the issue is that the value is not coming under sub array i.e.

[ { "id": 12 "lineid": 1234, "id": 12, "lineid": 98745 } ]


Solution

  • Hi I see two things in your script One is that the inner map should be details and not Header (I imagine this is a copy paste or problem simplification issue when copying it into stackoverflow as it doesn't work otherwise). The other problem is the use of { with an expressions enclosed with (

    {    
         (
            (payload01.Header map ( payload02, indexOfPayload02 ) -> {
                id: payload01.Header.id,
                lineid: payload02.lineid
            }) 
         )
    }
    

    This kind of syntax expands the array inside the object see https://docs.mulesoft.com/mule-runtime/4.1/dataweave-types#dynamic_elements

    So if you change it to

    payload map ((payload01, indexOfPayload01) -> 
      payload01.details map (payload02, indexOfPayload02) -> {
        id: payload01.Header.id,
        lineid: payload02.lineid
      })
    

    It produces

    [
      [
        {
          "id": 12,
          "lineid": 1234
        },
        {
          "id": 12,
          "lineid": 98745
        }
      ]
    ]