0

Im using Mule dataweave, here is my request, i want to filter my request to code == "P" if request containing Code = p not present then always default to code == "C" because code = C always present in the incoming request.

Request:

{
   "addresses": [
     {
        "contact": 0,
        "code": "P",
        "TypeDescription": "POSTAL",
        "postcode": "1007",
        "State": "TamilNadu",
        "Description": "Test",         
    },
    {
        "contact": 1,
        "code": "C",
        "TypeDescription": "PHYSICAL",
        "postcode": "Bangalore",
        "State": "",
        "Description": "NEW",

    }
 ] 
}

Dataweave:

 %dw 1.0
 %output application/json
 ---
 payload.addresses filter $.code == "P"  

It is working fine and filtering out the P containing list, but when try filter in combination with default it dont wont.

I have tried as below in dataweave payload.addresses filter $.code == "P1" default "anything here as of now".

Since in the above response i'm filtering P1 which is not present in the request hence im expecting the default stuff in the response. But it is not working.

Note: Using when and otherwise, bringing the list twice. I need only one list as response either Code P containing list or C containing list.

Using MUle 3.8.5 V. Please let me know your thoughts. Thanks in advance.

star
  • 1,493
  • 1
  • 28
  • 61

3 Answers3

1

From what I understand, Dataweave works from right to left, so in this case is evaluating like this:

  1. '"P1" default "anything here as of now"' resolves to "P1"
  2. run 'filter $.code == "P1"' over 'payload.addresses'

Of course that first option will always evaluate to "P1" so the default is essentially ignored. You need to use parentheses around the rest of the expression, then follow it with default. Now it will evaluate the parentheses then the default expression.

eg: (payload.addresses filter $.code == "P1") default "anything here as of now"

This is not a good example though, as filter will return an empty list if none of the options match, not null, so the default won't work. You could try something like in this answer: https://stackoverflow.com/a/44431546/2614624

Clinton Murdoch
  • 453
  • 4
  • 9
  • Upvoting this , it gave a hint for the solution - Filter returns Empty array not null. I figured out the solution as above. Thanks a lot – star Mar 14 '18 at 23:42
0

Create a default value in local variable and use an OR condition while filtering. Example below.

{
  biggerThanTwo: [0, 1, 2, 3, 4, 5] filter (($ > 2) OR ($ ==1))
}
Srinivas
  • 92
  • 3
0

Here is my Solution. As @Clinton mentioned Filter returns Empty array not null, here is the way it worked out

%dw 1.0 %output application/java

%var conditionalRoute = payload.addresses filter $.addressTypeCode == "P"

conditionalRoute when conditionalRoute != [] otherwise "anything here as of now"

star
  • 1,493
  • 1
  • 28
  • 61