2

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

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks :) Even though it works it is not what I want. I want to specify the fields that I want in the mapping.
0

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.