clare
clare

Reputation: 526

Transform list of objects into csv using dataweave

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

Upvotes: 2

Views: 8486

Answers (4)

user6017600
user6017600

Reputation:

For me, similar as @Tilo descirbed in his post, but I had to put extra "flatten" because I had Array of Arrays as my input.

MAPPING:

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

Upvotes: 0

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

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

Upvotes: 0

mtorsing
mtorsing

Reputation: 19

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

Upvotes: 1

Shoki
Shoki

Reputation: 1538

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.

Upvotes: 6

Related Questions