【问题标题】:Mulesoft 3 DataWeave - split a string by an arbitrary lengthMulesoft 3 DataWeave - 按任意长度分割字符串
【发布时间】:2020-12-22 00:34:51
【问题描述】:

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

【问题讨论】:

    标签: xml split dataweave mulesoft


    【解决方案1】:

    试试这个托尼:

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

    【讨论】:

    • 看起来不错,谢谢!那 40 是可配置的正则表达式吗,例如作为属性或 dw 常量?
    猜你喜欢
    • 2020-12-19
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多