gpt4 book ai didi

Dataweave 2.0 - 创建树状结构的 xml

转载 作者:行者123 更新时间:2023-12-01 23:50:56 26 4
gpt4 key购买 nike

我有如下从数据库中检索到的对象的 json 数组

[
{ "Projectid":"A1234","ProjectLvl":1,"desc":"A1234-desc"},
{ "Projectid":"A1234.1","ProjectLvl":2,"desc":"A1234.1-desc"},
{ "Projectid":"A1234.1.1","ProjectLvl":3,"desc":"A1234.1.1-desc"},
{ "Projectid":"A1234.1.1.1","ProjectLvl":4,"desc":"A1234.1.1.1-desc"},
{ "Projectid":"A1234.2","ProjectLvl":2,"desc":"A1234.2-desc"},
{ "Projectid":"A1234.2.1","ProjectLvl":3,"desc":"A1234.2.1-desc"}
]

我必须创建以下 xml。你能帮助 dataweave 函数在 mule 转换组件中使用吗?

<projects>
<project level="1">
<desc>A1234-desc</desc>
<project level="2">
<desc>A1234.1-desc</desc>
<project level="3">
<desc>A1234.1.1-desc</desc>
<project level="4">
<desc>A1234.1.1.1-desc</desc>
</project>
</project>
</project>
<project level="2">
<desc>A1234.2-desc
</desc>
<project level="3">
<desc>A1234.2.1-desc
</desc>
</project>
</project>
</project>
</projects>

最佳答案

你好,好问题我的解决方案尝试使用树上的 reduce 和递归更新来使用来自 ids 的路径更新节点

%dw 2.0
output application/xml

fun updateTree(tree, path: Array<Number>, treeNode: {}) = do {
if(sizeOf(path) == 1)
tree ++ treeNode
else
tree mapObject ((value, key, index) ->
if(index + 1 == path[0] and key ~= "project")
{
(key): updateTree(value, path[1 to -1], treeNode)
}
else
{
(key):value
}
)
}
---
projects: {
(
payload reduce ((project, accumulator = {}) -> do {
var path = project.Projectid[sizeOf("A1234") to -1] default "" splitBy "." filter !isEmpty($) map $ as Number
---
updateTree(accumulator,path,{
project @(level: project.ProjectLvl): {
desc: project.desc
}
})
}
)
)
}

关于Dataweave 2.0 - 创建树状结构的 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63515277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com