Search code examples
dataweavemulesoftanypoint-studiomule4anypoint-platform

Reading an attribute based on a condition using dataweave 2.0 from JSON array


Im trying to read an array of json payload and based on one attribute i like to pick elements. That is, I get array of employee data, based on termination date, i need to get who left the company.

Sample payload;

{
  "Employees": {
    "Employee": [
      {
        "UserId": "JC00",
        "TerminationDate": "2022-10-15"
      },
       {
        "UserId": "JC01",
        "TerminationDate": "2021-11-15"
      },
       {
        "UserId": "JC02",
        "TerminationDate": "2021-03-15"
      }
    ]
  }
}

My sample script is;

%dw 2.0
output application/json
---
{   
    responses: payload.Employees.Employee map ((employees, indexOfInv) -> 
   {
        staff: if(employees.'TerminationDate'<now()) employees.UserId else ''       
    })
}

My expected output is;

 {
      "responses": [
        {
          "UserId": "JC01"
        },
        {
          "UserId": "JC02"
        }
      ]
    }

But what i get currently is; "Cannot coerce String ("2022-10-15") to Null

Can anyone point me how to change TerminationDate to Date and compare with current date in Mule4?


Solution

  • DW

    You can filter out TerminationDate based on current date and then map it to remove the TerminationDate field. you should use as Date to convert string to date

    %dw 2.0
    output application/json
    ---
    "responses":(payload.Employees.Employee 
                  filter(($.TerminationDate as Date) < (now() as Date))
                    map($ - "TerminationDate"))
    

    Output

    {
      "responses": [
        {
          "UserId": "JC01"
        },
        {
          "UserId": "JC02"
        }
      ]
    }