DataWeave Delight: Convert string value to a boolean
If we need to convert a string value "true"
or "false"
to a boolean we can use the toBoolean
function from the dw::util::Coercions
module. The function will return a boolean true
if the string value is "true"
, mixed casing is allowed. And the function returns false
for a mixed casing string value of "false"
. Any other string value will throw an exception and will not return a boolean value.
In the following example we coerce some string values to a boolean and also include an example where the input value cannot be coerced:
Source
%dw 2.0
import try from dw::Runtime
import toBoolean from dw::util::Coercions
output application/json
---
{
// Coerce all string values to a boolean with value true.
trueBooleans: ["TRUE", "true", "True", "trUE"] map (s) -> toBoolean(s),
// Coerce all string value to a boolean with value false.
falseBooleans: ["FALSE", "false", "False", "falSE"] map toBoolean($),
// An exception is thrown when the string value cannot be coerced.
invalidCoercion: try(() -> toBoolean("Yes"))
}
Output
{
"trueBooleans": [
true,
true,
true,
true
],
"falseBooleans": [
false,
false,
false,
false
],
"invalidCoercion": {
"success": false,
"error": {
"kind": "InvalidBooleanException",
"message": "Cannot coerce String (Yes) to Boolean",
"location": "\n16| invalidCoercion: try(() -> toBoolean(\"Yes\"))\n
^^^^^",
"stack": [
"toBoolean (main:16:42)",
"main (main:16:32)"
]
}
}
}
DataWeave is a functional language designed by MuleSoft for transforming data structures defined in for example JSON, XML or CSV. |
Written with DataWeave 2.4.