【问题标题】:Reducing a String to array on Fixed length in Dataweave 2.0在 Dataweave 2.0 中将字符串减少为固定长度的数组
【发布时间】:2021-12-02 23:29:59
【问题描述】:

大家好,我正在寻找数据编织 2.0 Logic 中问题的解决方案或想法

问题是如果字符串超过最大长度,则将字符串转换为多个数组

最大长度为 8

{"message" : "hello this is Muley"}

expected output is 
{
 "message": ["hello", "this is", "muley"]
}

我已经尝试使用地图和临时变量来存储值,但它给出了一个空数组

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

输出是

{
    "message": [ "" ]
}

【问题讨论】:

  • 预期的输出是 { "message": ["hello", "this is", "muley"] } 还是 { "message": ["hello", "this", "is ", "骡子"] }
  • 例外是 { "message": ["hello", "this is", "muley"] } 因为如果我想要 { "message": [" hello", "this", "is", "muley"] } 我可以简单地使用 {message: payload.message splitBy(" ")}
  • 是的,这样每个数组元素都将在输出的新行中打印

标签: arrays loops reduce dataweave mule4


【解决方案1】:

由于空格的条件,它有些复杂。为了清楚起见,我试图将其封装到函数中。

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

我不确定您是否知道 DataWeave 是一种变量不可变的函数式语言。不能修改“临时”变量,只能返回新值。我使用递归函数来实现结果。

【讨论】:

    【解决方案2】:
    %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)
    

    感谢@aled提出DW中的递归和新技巧

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      相关资源
      最近更新 更多