Transform list of objects into csv using dataweave

老子叫甜甜 提交于 2019-12-11 03:36:57

问题


I am trying to transform a list of objects to csv using the following code in dataweave:

%dw 1.0
%type company = :object {class: "java.util.ArrayList"}
%input payload application/java
%output application/csv
---
{
    name: payload.name,
    address: payload.address
} as :company 

The below is the output that I get when I execute the above data weave code.

name,name
testName,testName2
testAddress,testAddress2

whilst I am expecting the following: (Sample data)

name,address
testName,testAddress
testName2,testAddress2

Help me understand to what am I missing in the data weave component


回答1:


In general terms, when using DataWeave you describe your output using a canonical representation which is more or less a super-set of other data formats.

To generate a CSV output you need to generate an array of objects.
Each of these objects represent a CSV row.
Objects in DataWeave are sets of key-value pairs

The mapping should be something like:

%dw 1.0
%output application/csv
---
payload map {
    name: $.name,
    address: $.address
}

The map operation here generates an object with a name and address for each entry in the list. $ represents the implicit variable under iteration (each list entry).

Note: The %input payload application/java directive is not necessary since the content-type for your input (JSON, XML, CSV, etc) is taken from the mule message when it is set, and it defaults to java if it's not present.




回答2:


The following works for me:

INPUT:

%dw 1.0
%output application/java
---
[{
    name: "nameInput",
    address: "addressInput"
}]

MAPPING:

%dw 1.0 %output application/csv
---
payload

OUTPUT:

name,address
nameInput,addressInput



回答3:


A splitter with xpath as evaluator should do the trick...like:

<splitter evaluator="xpath" expression="/document/article"/>


来源:https://stackoverflow.com/questions/32202884/transform-list-of-objects-into-csv-using-dataweave

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!