Search

Dark theme | Light theme

February 10, 2022

DataWeave Delight: Turn string value into array of characters

A string value can be seen as an array of characters and if we want to transform our string value to an array we can use the toArray function in the dw::util::Coercions module. Once we have transformed our string to an array we can use all functions that work on arrays. The nice thing about DataWeave is that some functions that work on arrays already have an overloaded version that accepts a string value. Then we don't have to explicitly use the toArray function, but we can simply use our original value when we invoke the function.

In the following example we use the toArray function and also see the groupBy function that already accepts a string value and treats it is as an array:

Source

%dw 2.0

import toArray from dw::util::Coercions
import isUpperCase from dw::core::Strings

output application/json
---
{
    // toArray will convert a string to an array of characters
    toArray: toArray("DataWave"),
    
    // joinBy function only accepts an array argument
    toArrayJoinBy: toArray("abcd") joinBy "-",

    // groupBy function has been overloaded to accept string,
    // but internally makes it an array of characters
    groupByString: "AbCd" groupBy ((character, index) -> isUpperCase(character))
}

Output

{
  "toArray": [
    "D",
    "a",
    "t",
    "a",
    "W",
    "e",
    "a",
    "v",
    "e"
  ]
  "toArrayJoinBy": "a-b-c-d",
  "groupByString": {
    "true": "AC",
    "false": "bd"
  }
}

Written with DataWeave 2.4.