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

问题描述

在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 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可以使用定界符,但是我想使用任意长度。

解决方法

尝试这个Tony:

%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",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}
    )
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...