1
votes

I am using Anypoint Studio 6.1 and Mule 3.8.1 and am mapping JSON to JSON in Dataweave. In the JSON mapping I have an optional field called "Channels" which contains a list of strings. When the field is not there I get a warning in Dataweave. How can I write the Dataweave code to ignore if its null?

Dataweave code:

%dw 1.0
%output application/json skipNullOn="everywhere"
---
payload map ((payload01 , indexOfPayload01) -> {
    Channels: payload01.Channels map ((channel , indexOfAccessChannel) -> channel)
})

I have tried to use "when" and also the "?" selector modifier but cannot get the syntax right.

Thanks

1

1 Answers

2
votes

You were right to use when and the ? operator. You just need to use parentheses to make sure they apply to the right things. Note that I am using $ as a shorthand for the payload01 parameter in your example.

%dw 1.0
%output application/json

---
payload map {
    (Channels: $.Channels map (lower $)) when $.Channels?
}

If you didn't need to use map on the Channels array within each item, you could just allow the null to pass through:

payload map {
    Channels: $.Channels
}

This would yield the following for input objects that don't contain a Channels field:

{
    Channels: null
}

Adding the parentheses allows us to use when to determine whether the whole key/value pair (aka tuple) should be output:

payload map {
    (Channels: $.Channels) when $.Channels?
}

Yielding:

{
}