Mulesoft 3 DataWeave — разделить строку на произвольную длину

#xml #split #dataweave #mulesoft

#xml #разделение #dataweave #mulesoft

Вопрос:

Как в 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 что можно использовать разделитель, но я хочу использовать произвольную длину.

Ответ №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}
    )
}
  

Комментарии:

1. Выглядит хорошо, спасибо! Является ли 40 настраиваемым регулярным выражением, например, как свойство или константа dw?