Search code examples
mulemule-studiomule-componentmule-el

How to Check null condition in Data weaver : Mule


Here is my xml, in that first I need to check 'RecordsEntries' should not be 'null', then RecordEntry shouldn't be null followed by mapping code

<?xml version="1.0" encoding="UTF-8"?>
<Records>
  <storenumber />
  <calculated>false</calculated>
  <subTotal>12</subTotal>
 <RecordsEntries>
   <RecordEntry>
     <deliverycharge>30.0</deliverycharge>
     <entryNumber>8</entryNumber>
     <Value>true</Value>
  </RecordEntry>
  <RecordEntry>
    <deliverycharge>20.0</deliverycharge>
    <entryNumber>7</entryNumber>
    <Value>false</Value>
  </RecordEntry>
</RecordsEntries>
 <RecordsEntries>
    <RecordEntry>
      <deliverycharge>30.0</deliverycharge>
      <entryNumber>8</entryNumber>
      <Value>false</Value>
    </RecordEntry>
 </RecordsEntries>
</Records>

Tried multiple scenario's also used when condition checking but somewhere missing parenthesis or correct format

    orders: {
    order: {
  StoreID: payload.Records.storenumber,
  Total: payload.Records.calculated,
 (( payload.Records.RecordsEntries.*RecordEntry ) map {
    IndividualEntry: {
    Number:$.entryNumber,
    DeliverCharge:$.deliverycharge
    }
  } when ( payload.Records.RecordsEntries != null and payload.Records.RecordsEntries.*RecordEntry !=null))}
}

getting error like missing ). Tried other way around by checking the null condition directly inside the first loop got error like "Cannot coerce array to an boolean". Please suggest. Thanks.


Solution

  • You can instead do

    %dw 1.0
    %output application/xml
    ---
    orders: {
      order: {
      StoreID: payload.Records.storenumber,
      Total: payload.calculated,
     ((payload.Records.*RecordsEntries.*RecordEntry default []) map {
          IndividualEntry: {
            Number:$.entryNumber,
            DeliverCharge:$.deliverycharge
          }
        })
      }
    }
    

    DataWeave is "null-safe" for querying values like in payload.Records.*RecordsEntries.*RecordEntry, but an error will be thrown when trying to operate with a null (e.g. null map {}).

    The default operator replaces the value to its left, if it's null, with the one on the right.

    Also you were missing an *. You need to use it in xml whenever you want all the repetitive elements that match.