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": [ "" ]
}
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.
%dw 2.0
fun strtoarr(string :String ,cap:Number)=do
{
var size=sizeOf(string)
var ind=(
if(size >= cap)
(
if((string[0 to cap] lastIndexOf(" ")) == -1)
(string indexOf(" "))
else
(string[0 to cap] lastIndexOf (" "))
)
else
size
) -1
var str=string[0 to ind]
---
flatten([str] ++ (if(size > cap) strtoarr(string[ind+2 to -1],cap) else []) )
}
---
strtoarr("hello this is Muley",8)
thanks to @aled for suggesting the recursion and new trick in DW
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.