Search code examples
muledataweavemule-esbmulesoft

Nested Loop to generate a json array


I have a requirement to enter two objects in a json array for each object in the input.

I wrote the following code to do so:

%dw 2.0
output application/csv
var categoryList = ["Business","Authorization"]
---
payload map((payload01,indexOfPayload01)->
categoryList map((payload02,indexOfPayload02)->
    {
    "Name": payload01.Name,
    "Category":payload02,
    "Code":"Customer",
    "Percentage":null,
    "End Tag": "End"
    })
)

My output is:

[
  [
    {
      "Name": "Desc 1",
      "Category": "Business",
      "Code": "Customer",
      "Percentage": null,
      "End Tag": "END"
    },
    {
      "Name": "Desc 1",
      "Category": "Authorization",
      "Code": "Customer",
      "Percentage": null,
      "End Tag": "END"
    }
  ],
  [
    {
      "Name": "Desc 2",
      "Category": "Business",
      "Code": "Customer",
      "Percentage": null,
      "End Tag": "END"
    },
    {
      "Name": "Desc 2",
      "Category": "Authorization",
      "Code": "Customer",
      "Percentage": null,
      "End Tag": "END"
    }
  ]
]

But I wanted the values as a single json array. Here the data was separated as two objects. My Expected output:

[
    {
      "Name": "Desc 1",
      "Category": "Business",
      "Code": "Customer",
      "Percentage": null,
      "End Tag": "END"
    },
    {
      "Name": "Desc 1",
      "Category": "Authorization",
      "Code": "Customer",
      "Percentage": null,
      "End Tag": "END"
    },
    {
      "Name": "Desc 2",
      "Category": "Business",
      "Code": "Customer",
      "Percentage": null,
      "End Tag": "END"
    },
    {
      "Name": "Desc 2",
      "Category": "Authorization",
      "Code": "Customer",
      "Percentage": null,
      "End Tag": "END"
    }
]

How can I get this done? Needless to say, I am new to Mule.

Thanks, Anoop


Solution

  • You can use flatMap as I'm showing in this example, or flatten the result as the example 2

    %dw 2.0
    output application/csv
    var categoryList = ["Business","Authorization"]
    ---
    payload flatMap((payload01,indexOfPayload01)->
    categoryList map((payload02,indexOfPayload02)->
        {
        "Name": payload01.Name,
        "Category":payload02,
        "Code":"Customer",
        "Percentage":null,
        "End Tag": "End"
        })
    )
    

    This example shows how to use flattn

    %dw 2.0
    output application/csv
    var categoryList = ["Business","Authorization"]
    ---
    flatten(payload map((payload01,indexOfPayload01)->
    categoryList map((payload02,indexOfPayload02)->
        {
        "Name": payload01.Name,
        "Category":payload02,
        "Code":"Customer",
        "Percentage":null,
        "End Tag": "End"
        })
    ))