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.