Converting CSV to array using DataWeave

2019-09-04 08:00发布

问题:

I'm using Mule Requester to load a CSV file. After the file is loaded, the payload is a byte array, which I store in a flow variable, mycsv. I keep getting an exception.

org.mule.api.MessagingException: Exception while executing: 
    NetIds: flowVars.mycsv map $."My Column Name"   
                        ^
Cannot coerce a :binary to a :array (com.mulesoft.weave.mule.exception.WeaveExecutionException). Message payload is of type: byte[]

Here's my DataWeave code:

%dw 1.0
%output application/java
---
{
    Values: flowVars.mycsv map $."My Column Name"
}

The previous flow element is a choice, so I set the metadata on that to output to a FlowVar with the right name and referenced a sample CSV file, so DataWeave things the variable type is List<Csv>.

How can I read the CSV? Thanks!

回答1:

It's because it doesnt know the mimeType of the flowVar because it's not set. Try this before the dataweave transformer:

<set-variable value="#[flowVars.mycsv]" variableName="mycsv" mimeType="application/csv" doc:name="Variable" />

or set the mimeType when you first read the csv.



回答2:

This is the first time I found a requirement to put two different formats into one csv file. In order to get the expected result, I prefer to use this trick: Create both expressions and combine them into one simple array, using flatten Add an empty object as line separator