首页 > 解决方案 > 在dataweave 2.0中的字符串中插入字符

问题描述

输入:

{
  "string": "putbackthespaces",
  "indexes": [
    3,
    8,
    12
  ]
}

输出:

{
  "string": "put back the spaces"
}

我想在 payload.indexes 中的元素指定的特定索引处插入一个字符(在此特定示例中,将插入空格)。这里的问题是只能使用 mule 流和 dataweave 来完成转换。谢谢!

标签: dataweaveanypoint-studiomulesoft

解决方案


我使用递归函数为每个字符应用插入:

%dw 2.0
output application/json
import * from dw::core::Arrays
fun insertChar(s, n, c)=s[0 to n-1] ++ c ++ s[n to -1]
fun insertAllChars(s, a, c)=
    if (sizeOf(a)>0) 
        insertAllChars(
            insertChar(s, a[0], c), 
            slice(a,1, sizeOf(a)), 
            c
        ) 
    else s
---
{
    string: insertAllChars(payload.string, payload.indexes , " ")
}

推荐阅读