Search

Dark theme | Light theme
Showing posts with label DataWeave:String. Show all posts
Showing posts with label DataWeave:String. Show all posts

February 15, 2022

DataWeave Delight: Trimming string values

In DataWeave we can use the trim function from the dw::Core module to remove any space character before and after a string value. The characters that are removed are the space, tab and newline characters. There is an overloaded function definition that will accept a null value and returns a null value.

In the following example we trim string values that start and end with spaces, tabs and newline characters:

Source

%dw 2.0

output application/json
---
{
    // Spaces at the start and end ar removed.
    spaces: trim("   mrhaki  "),

    // Also tabs are removed.
    tabs: trim("\t mrhaki"),

    // And newline characters are removed
    newline: trim("\tmrhaki \r\n"),

    // trim will return null when a null value is used.
    nullValue: trim(null),
}

Output

{
  "spaces": "mrhaki",
  "tabs": "mrhaki",
  "newline": "mrhaki",
  "nullValue": null
}

Written with DataWeave 2.4.

February 14, 2022

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)"
      ]
    }
  }
}

Written with DataWeave 2.4.

February 10, 2022

DataWeave Delight: Padding strings

In DataWeave we can create a fixed width string value. If the string value is less than the fixed width than the space is padded with spaces or any other character we want. We can add the padding to the left of our string value or to the right. For left padding we use the function leftPad from the dw::core::Strings module. And for right padding we use the function rightPad in the same module. The functions takes as first argument the string value, the second argument is the total width of the resulting string and the third optional argument is the character we want to use for padding. By default the padding character is a space (" "), but we can use any character. We must make sure we only use 1 character, because when we use more than 1 character the result is no longer a string value with our defined maximum width.

In the following example we use both functions with several arguments:

Source

%dw 2.0

import rightPad, leftPad from dw::core::Strings

var text = "DataWeave"

output text/plain
---
"|$(text)|
|$(rightPad(text, 12))| 
|$(rightPad(text, 12, "*"))|
|$(leftPad(text, 12))|
|$(leftPad(text, 12, "-"))|

Using multiple characters for padding 
gives unexpected result:
|$(rightPad(text, 12, " * "))| 
"

Output

|DataWeave|
|DataWeave   | 
|DataWeave***|
|   DataWeave|
|---DataWeave|

Using multiple characters for padding 
gives unexpected result:
|DataWeave *  *  * | 

In the following example we use the leftPad and rightPad functions to generate a report as text.

%dw 2.0

import rightPad, leftPad from dw::core::Strings

var data = [
    { page: "page1.html", responseTime: 200, size: 1201 },
    { page: "page2.html", responseTime: 42,  size: 8853 },
    { page: "page3.html", responseTime: 98,  size: 3432 },
    { page: "page4.html", responseTime: 432, size: 9081 },
]

fun total(index) = data reduce ((row, result = 0) -> result + row[index] as Number)

var totalTime = total(1)
var totalSize = total(2)

output text/plain
---
"
*** Summary ***

$(rightPad("Total pages", 25)): $(leftPad(sizeOf(data) as String, 6))
$(rightPad("Total response time (ms)", 25)): $(leftPad(totalTime as String, 6))
$(rightPad("Total size (KB)", 25)): $(leftPad(totalSize as String, 6))

*** Details ***

$(data map ((item) -> rightPad(item.page, 14) ++ 
                      leftPad(item.responseTime, 5) ++ 
                      leftPad(item.size, 8)) 
       joinBy "\n")
"

Output


*** Summary ***

Total pages              :      4
Total response time (ms) :    772
Total size (KB)          :  22567

*** Details ***

page1.html      200    1201
page2.html       42    8853
page3.html       98    3432
page4.html      432    9081

Written with DataWeave 2.4.