0

In Mulesoft (version 4.2.1), I'm getting CSV file as input and in headers, I'm getting some spaces along with header name, which I'm not expecting. For example, I'm getting, 'FirstName ' instead of 'FirstName'. How to remove extra spaces from header, before processing.

Kiran
  • 29
  • 1
  • 8

3 Answers3

2

This is one way to do it.

%dw 2.0
output application/json
import * from dw::core::Objects
var headers=keySet(payload[0]) reduce ((key, acc = {}) -> acc ++ { (trim(key)): key})
fun searchKeyTrimmed(row, h)=row[headers[h]]
---
payload map {
    a: searchKeyTrimmed($,'a'),
    b: searchKeyTrimmed($,'b')
}

Input:

a , b,c,d 
1,2,3,4

Output:

[
  {
    "a": "1",
    "b": "2"
  }
]
aled
  • 21,330
  • 3
  • 27
  • 34
0

Mulesoft is only transformation engine in your case. It has nothing to do with spaces in the header. If header has 'FirstName ' then you should use this column name as is. Or you can transform it to another name with extra transformation like this:

%dw 2.0
output application/json
---
{
    FirstName: payload['FirstName ']
}
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Alex
  • 4,457
  • 2
  • 20
  • 59
  • thanks Alex, but as of now, I 've around 50 header in csv file and I do not know how many spaces I get in headers(some headers are not having spaces). Is there any way that I can dynamically handle this issue. – Kiran Mar 21 '20 at 18:03
0

map iterates over the items in the array. $ is the value (object).

mapObject iterated over the objects. $$ is the key (header in csv) and $ is the value (value in row for that particular key).

replace and with are used together to search the string (key), in our case for space (" ") and replace it with empty string (""). As a result, all the spaces in the headers would be removed.

%dw 2.0
output application/csv
---
payload map ($ mapObject ($$ replace " " with ""):$)

FYI - for json output format please update application/csv to application/json