从数组生成数组

时间:2019-08-03 19:29:24

标签: dataweave mulesoft

我输入的内容如下:

[
    {
        "Attachments": [
            {
                "FileType": "pdf"
            },
            {
                "FileType": "txt"
            }
        ],
        "Name": "test"
    },
    {
        "Attachments": [],
        "Name": "test2"
    }
]

]

我想要的输出是:

[
    {
        "FileType": "pdf",
        "Name": "test"
    },
    {
        "FileType": "txt",
        "Name": "test"
    },
    {
        "FileType": null,
        "Name": "test2"
    }
]

所以,问题是如何使用DataWeave 2.0为附件和名称的每种组合获取一个包含元素的数组?

1 个答案:

答案 0 :(得分:3)

此脚本可以,尽管我想知道它是否更简单:

%dw 2.0
output application/json
---
flatten(
    payload map ((item) -> 
        if (!isEmpty(item.Attachments)) 
            item.Attachments map ((value) -> 
                {
                    Name: item.Name,
                    FileType: value.FileType
                }
            ) 
        else {
            Name: item.Name,
            FileType: "null"
        } 
    )
)

输入:

[
    {
        "Name": "test",
        "Attachments": [{ "FileType": "pdf" }, { "FileType": "txt" }] 
    },{ 
        "Name": "test2", 
        "Attachments": [] 
    }
]

输出:

[
  {
    "Name": "test",
    "FileType": "pdf"
  },
  {
    "Name": "test",
    "FileType": "txt"
  },
  {
    "Name": "test2",
    "FileType": "null"
  }
]