使用 dataweave 将单列值转换为多行

问题描述 投票:0回答:1

我收到一个 JSON 有效负载,其中两列包含值数组。我们想要将数组列分成多行。

示例输入:

[
    {
        "firstName": "John",
        "surname": "Smith",
        "primarySkills": [
            "presentation",
            "developer"
        ],
        "secondarySkills": [
            "abc",
            "xyz"
        ],
        "email": "[email protected]",
        "phone": "1234567890"
    },
    {
        "firstName": "S",
        "surname": "D",
        "primarySkills": [
            "presentation"
        ],
        "secondarySkills": [
            "developer"
        ],
        "email": "[email protected]",
        "phone": "1234567890"
    }
]

预期输出:

[
    {
        "firstName": "John",
        "surname": "Smith",
        "primarySkills": "presentation",
        "secondarySkills": "abc",
        "email": "[email protected]",
        "phone": "1234567890"
    },
    {
        "firstName": "John",
        "surname": "Smith",
        "primarySkills": "developer",
        "secondarySkills": "xyz",
        "email": "[email protected]",
        "phone": "1234567890"
    }
    {
        "firstName": "S",
        "surname": "D",
        "primarySkills": "presentation",
        "secondarySkills": "developer",
        "email": "[email protected]",
        "phone": "1234567890"
    }
]

有人可以帮助我如何实现这一目标吗?

提前谢谢您

mule dataweave mulesoft mule4
1个回答
0
投票

假设两个嵌套数组具有相同的长度,您可以将每个技能映射到其父记录中,并使用第一个技能的索引添加第二个技能。使用 flatMap() 可以处理不需要的嵌套数组。

%dw 2.0
output application/json
---
payload flatMap ((item) -> 
    (item.primarySkills flatMap ((skill, index) -> 
        item - "primarySkills"  - "secondarySkills" 
            ++ {primarySkills: skill} 
            ++ {secondarySkills: item.secondarySkills[index]})
    )
)

输出:

[
  {
    "firstName": "John",
    "surname": "Smith",
    "email": "[email protected]",
    "phone": "1234567890",
    "primarySkills": "presentation",
    "secondarySkills": "abc"
  },
  {
    "firstName": "John",
    "surname": "Smith",
    "email": "[email protected]",
    "phone": "1234567890",
    "primarySkills": "developer",
    "secondarySkills": "xyz"
  },
  {
    "firstName": "S",
    "surname": "D",
    "email": "[email protected]",
    "phone": "1234567890",
    "primarySkills": "presentation",
    "secondarySkills": "developer"
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.