1

I have a few boolean fields in the payload, in any case only ONE field will be true. But sometimes payload will have only two of these boolean fields. I want to check if payload has this boolean field, then use it for mapping else ignore it.

Input payload:

{
 "IsTypeA" : true,
 "IsTypeB" : false,
 "IsTypeC" : false,
 "text1" : "abc",
 "text2" : "def"
}

Possible variation of input payload:

{
 "IsTypeB" : true,
 "IsTypeC" : false,
 "text1" : "abc",
 "text2" : "def"
}

I need to calculate the value of output field using IsTypeA,IsTypeB,IsTypeC only if they exist.

Pseudo code:

if IsTypeA exists
  result: if(IsTypeA == true) true else false
else if IsTypeB exists
  result: if(IsTypeB == true) true else false
else if IsTypeC exists
  result: if(IsTypeC == true) true else false
else false
aled
  • 21,330
  • 3
  • 27
  • 34
Abjt G
  • 39
  • 7

2 Answers2

2

You can check key is present or not using key? present selector

%dw 2.0
output application/json
---
"result":(if((payload."IsTypeA"?) and (payload.IsTypeA ==true))
    true
else if((payload."IsTypeB"?) and (payload.IsTypeB ==true))
    true 
else if((payload."IsTypeC"?) and (payload.IsTypeC ==true))
    true 
else false)    

Karthik
  • 2,181
  • 4
  • 10
  • 28
1

Another way to do this by using default. The default keyword sets the default value when the value is not present.

%dw 2.0
output application/json
---
result: (payload.IsTypeA default false) or (payload.IsTypeB default false) or (payload.IsTypeC default false)
aled
  • 21,330
  • 3
  • 27
  • 34
sudhish_s
  • 573
  • 2
  • 5
  • This answer does not return the expected response. Using `default` replaces the value if it is null. It is not the same as testing if the key is defined. For example if `payload.IsTypeA` is null (`{ "IsTypeA": null }`) then `payload.IsTypeA default false` returns `false` but `payload.IsTypeA?` returns `true`. – aled Dec 05 '22 at 16:46
  • I understand that the key presence will return `true` when the value is `null`. Thus for null scenario, even if`payload.IsTypeA?` returns `true`, the overall condition `payload.IsTypeA? and payload.IsTypeA == true` returns `false`. So I do not understand how the final result varies with the given answer. – sudhish_s Dec 05 '22 at 21:54
  • I see, I missed that you were not trying to replace the test for key present and instead it is testing for the value directly. Having said that, your script will work as long as the values are boolean, but it will throw an error otherwise. For example for `"IsTypeA": 1`. @Karthik scripts handles that case without an error. – aled Dec 05 '22 at 22:29
  • Yes, agreed, this will only works if inputs are boolean. And, as per OP, the inputs are all boolean. – sudhish_s Dec 05 '22 at 23:09