Mulesoft 3 DataWeave - 按任意长度拆分字符串

Mulesoft 3 DataWeave - split a string by an arbitrary length

在 Mule 3 DataWeave 中,如何将一个长字符串按设定长度拆分为多行?

例如,我有以下 JSON 输入:

{
   "id" : "123",
   "text" : "There is no strife, no prejudice, no national conflict in outer space as yet. Its hazards are hostile to us all. Its conquest deserves the best of all mankind, and its opportunity for peaceful cooperation many never come again."
}

输入系统只能接受40个字符以下的字符串,所以输出XML需要符合如下:

<data>
   <id>123</id>
   <text>
      <line>There is no strife, no prejudice, no nat</line>
      <line>ional conflict in outer space as yet. It</line>
      <line>s hazards are hostile to us all. Its con</line>
      <line>quest deserves the best of all mankind, </line>
      <line>and its opportunity for peaceful coopera</line>
      <line>tion many never come again.</line>
   </text>
</data>

我知道splitBy可以使用分隔符,但我想使用任意长度。

试试这个托尼:

%dw 1.0
%output application/xml
%var data = {
   "id" : "123",
   "text" : "There is no strife, no prejudice, no national conflict in outer space as yet. Its hazards are hostile to us all. Its conquest deserves the best of all mankind, and its opportunity for peaceful cooperation many never come again."
}
---
data: {
    id: data.id,
    text: data.text scan /.{1,40}/ reduce (
        (e,acc={}) -> acc ++ {text: e[0]}
    ) 
}

我不知道有什么方法可以在 DW 1.0 的正则表达式中动态注入范围值(我还没有检查,但我敢打赌这在 DW 2.0 中是可能的)。因此,我编写了一个 DW 1.0 函数,将 :string 值分成等份。这是知道您应该能够动态设置大小的转换:

%dw 1.0
%output application/xml
%var data = {
   "id" : "123",
   "text" : "There is no strife, no prejudice, no national conflict in outer space as yet. Its hazards are hostile to us all. Its conquest deserves the best of all mankind, and its opportunity for peaceful cooperation many never come again."
}

%function equalParts(str,sz)
    [str]
    when ((sizeOf str) < sz or sz <= 0) 
    otherwise
        using (
            partCoords = (0 to (floor (sizeOf str) / sz) - 1) map [$ * sz, $ * sz + sz - 1] 
        ) (
            
            partCoords + [partCoords[-1][-1]+1,-1] map 
                str[$[0] to $[1]]
        )

---
data: {
    id: data.id,
    text: equalParts(data.text,40) reduce (
        (e, acc={}) -> acc ++ {text: e}
    )
}