Home > front end >  Reducing a String to array on Fixed length in Dataweave 2.0
Reducing a String to array on Fixed length in Dataweave 2.0

Time:10-15

Hello guys i'm looking for a solution or ideas to the problem in data weave 2.0 Logic

problem is to convert an string to multiple arrays if the string crosses the max length

max length is 8

{"message" : "hello this is Muley"}

expected output is 
{
 "message": ["hello", "this is", "muley"]
}

i have tried the map and temporary variable to store the values but it was giving an null array

%dw 2.0
output application/json
var tmp=[[]]
var max=8
fun ck(tmp,data)= 
    (
    if(sizeOf((tmp[-1] joinBy (" ")  default "")   " "    data) <= max ) 
       (tmp[-1] << data) 
    else 
        tmp << [data]
    )
var msd=(payload.message splitBy(" ") map(item, value) -> (ck(tmp, item)))
---
{"message": tmp map()-> $ joinBy  " "} 

output is

{
    "message": [ "" ]
}

CodePudding user response:

It is somewhat complex because of the condition on spaces. I have tried to encapsulate that into functions for clarity.

%dw 2.0
output application/json
import * from dw::core::Strings
import * from dw::core::Arrays
fun findNextSpace(s, max)=do {
    var spaces = find(s, " ")
    var overIndex=spaces indexWhere ($ > max - 1)
    var firstSpaceBeforeMax = spaces[if (overIndex > 0) (overIndex  - 1) else -1]
    ---
    firstSpaceBeforeMax
}

fun splitMax(data, max)= 
    if (sizeOf(data) >= max)
        flatten([data[0 to findNextSpace(data, max) - 1],splitMax(data[findNextSpace(data, max)   1 to -1], max) ])  
    else
        data
---
{
    message: splitMax(payload.message, 8)
}

I'm not sure if you are aware that DataWeave is a functional language where variables are immutable. It is not possible to modify a 'temporary' variable, only to return new values. I used a recursive function to achieve the result.

  • Related