Search code examples
dataweave

Reading From an Array within an Array in Dataweave


I am trying to create an output JSON Array object from a JSON source with subarrays within the parent Array object and not able to figure the right dataweave to traverse the subarray. The target JSON array should be repeating elements from source subarray ExpenseReportDetailArray. Here is the source JSON Array with the subarray:

[
    {
        "ExpenseReportHeader": {
            "ReportName": "Jane Zoe ExpensesX"
        },
        "ExpenseReportDetailArray": [
            {
                "CityStart": "CLT",
                "CityEnd": "AUS"
            },
            {
                "CityStart": "AUS",
                "CityEnd": "CLT"
            }
        ]
    },
    {
        "ExpenseReportHeader": {
            "ReportName": "Jane Zoe ExpensesY"
        },
        "ExpenseReportDetailArray": [{
            "CityStart": "CLT",
            "CityEnd": "AUS"
        }]
    }
]

Here is the target JSON Array:

[
    {
        "Name": "from source X",
        "SourceCity": "from source ExpenseReportDetailArray[x]",
        "DestinationCity": "from source ExpenseReportDetailArray[x]",
    },
    {
        "Name": "from source",
        "SourceCity": "from source ExpenseReportDetailArray[x+1]",
        "DestinationCity": "from source ExpenseReportDetailArray[x+1]",
    },
    {
        "Name": "from source Y",
        "SourceCity": "from source ExpenseReportDetailArray[y",
        "DestinationCity": "from source ExpenseReportDetailArray[y]",
    }
]
%dw 2.0
output application/java
---
payload map ( payload01 , indexOfPayload01 ) -> {
    Name: payload01.ExpenseReportHeader.ReportName,
    payload01 map () -> {
        SourceCity: payload01.ExpenseReportDetailArray.CityStart,
        DestinationCity: payload01.ExpenseReportDetailArray.CityEnd
    }
}

Solution

  • You can use flatMap() to avoid nesting arrays. Then map each record in the child arrays and insert the name from the parent there. I'm using a JSON output for clarity. You can change it back to Java:

    %dw 2.0
    output application/json
    ---
    payload flatMap (( payload01 , indexOfPayload01 ) -> 
            payload01.ExpenseReportDetailArray map  {
                Name: payload01.ExpenseReportHeader.ReportName,
                SourceCity: $.CityStart,
                DestinationCity: $.CityEnd
            }
    )
    

    Output (after removing extra commas in the input):

    [
      {
        "Name": "Jane Zoe ExpensesX",
        "SourceCity": "CLT",
        "DestinationCity": "AUS"
      },
      {
        "Name": "Jane Zoe ExpensesX",
        "SourceCity": "AUS",
        "DestinationCity": "CLT"
      },
      {
        "Name": "Jane Zoe ExpensesY",
        "SourceCity": "CLT",
        "DestinationCity": "AUS"
      }
    ]