问题描述
我有一个带有单个索引的数组,该数组有一个 JSON 对象,该对象包含三个不同的字符串数组,我必须根据每个索引将它们映射为一个。例如,将每个数组中的所有第一个索引转换为一个 JSON 对象,依此类推...
Dataweave Transformation 中是否有可能?
输入
[{
"id": [
"123","456","789"
],"name": [
"Test Brand 1","Test Brand 2","Test Brand 3"
],"address": [
"Via Roma 1","Via Milano 1","Via Napoli 1"
]
}]
所需的输出:
[
{
"Key1": "123","Key2": "Test Brand 1","Key3": "Via Roma 1"
},{
"Key1": "456","Key2": "Test Brand 2","Key3": "Via Milano 1"
},{
"Key1": "789","Key2": "Test Brand 3","Key3": "Via Napoli 1"
}
]
解决方法
您可以尝试以下 DataWeave 表达式,假设每个数组将始终包含相同数量的项目:
%dw 2.0
output application/json
---
flatten(payload map (item,index1) ->
item.id map (item2,index2) -> {
"Key1": item2,"Key2": item.name[index2],"Key3": item.address[index2]
})
输出(地址名称已更改以确保转换按预期工作):
[
{
"Key1": "123","Key2": "Test Brand 1","Key3": "Via Roma 1"
},{
"Key1": "456","Key2": "Test Brand 2","Key3": "Via Milano 2"
},{
"Key1": "789","Key2": "Test Brand 3","Key3": "Via Napoli 3"
}
]
,
您可以尝试下面的代码,其中我们不需要进行两次迭代(循环)并且不需要展平。
%dw 2.0
output application/json
var id = payload[0].id
---
id map (item2,"Key2": payload[0].name[index2],"Key3": payload[0].address[index2]
}
它会给出相同的结果。
[
{
"Key1": "123","Key3": "Via Milano 1"
},"Key3": "Via Napoli 1"
}
]
谢谢
,我对此进行了调整,只是为了使其具有动态性,以便它适用于数组中的任意数量的键。由于您无法访问reduce中的索引,因此有点令人困惑。享受!
%dw 2.0
output application/json
import indexOf from dw::core::Arrays
var data = [{
"id": [
"123","456","789"
],"name": [
"Test Brand 1","Test Brand 2","Test Brand 3"
],"address": [
"Via Roma 1","Via Milano 1","Via Napoli 1"
]
}]
---
(data flatMap valuesOf($)) map ((valuesArray) -> valuesArray reduce ((value,acc={}) -> acc ++ {
("key$(indexOf(valuesArray,value) + 1)"): value
}))
输出:
[
{
"key1": "123","key2": "456","key3": "789"
},{
"key1": "Test Brand 1","key2": "Test Brand 2","key3": "Test Brand 3"
},{
"key1": "Via Roma 1","key2": "Via Milano 1","key3": "Via Napoli 1"
}
]