使用 Dataweave 将多个字符串数组映射到单个数组中

Map multiple string Arrays using Dataweave into a single Array

我有一个带有单个索引的数组,它有一个包含三个不同字符串数组的 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, index2) -> {
        "Key1": item2,
        "Key2": payload[0].name[index2],
        "Key3": payload[0].address[index2]
    }

它会给出相同的结果。

[
  {
    "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"
  }
]

谢谢

我对此进行了尝试,只是为了使其动态化,以便它适用于数组中的任意数量的键。这有点令人困惑,因为您无权访问 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"
  }
]