How to map source fields to target fields from comma-separated string values
Content
The goal of this article is to write a DataWeave transformation that translates the source fields to target fields from a comma-separated string value.
For example, we have a list of source field names as input and the expected target field to be mapped before we pass this to the next component.
We want the following output:
Scenario 1:
Fields Transformation:
Input:
{
"columnList": "all"
}
Output:
{
"columnList": "all"
}
Scenario 2:
Fields Transformation:
Note: Additional checks
- Map only those fields listed in the above list.
- Trim spaces to avoid any mismatch with the field names.
- Remove duplicates in case of.
Recommended by LinkedIn
- Remove empty fields or null empty strings
Input:
{
"columnList": "siteName,network,productCode,productName"
}
Output:
{ "columnList": "merchantNameLocation,merchantNetwork,globalProductCode,globalProductDescription"
}
PROCEDURE
Using DataWeave inbuilt core functions we could achieve the above scenarios, the following expression implements the desired output:
DataWeave Input Scenarios:
Mixed Case
{
"columnList": "AlL"
}
{
"columnList": "aLl"
}
Duplicate Fields
{
"columnList": "siteName,network, siteName,productCode,productName"
}
Empty Strings
{
"columnList": "siteName,network, ,productCode, ,productName"
}
Spaces before or after fields
{
"columnList": "siteName,network,productCode, productName , "
}
camelize
{
"columnList": "SiteName,Network, ,productCode, ,productName"
}
DataWeave Script:
%dw 2.0
import * from dw::core::Strings
fun fromStringSourceFieldToTargetFields(string) =
if (lower(string) == "all")
"All"
else
trim(camelize(string)) splitBy "," map (trim($) match {
case "siteName" -> "merchantNameLocation"
case "network" -> "merchantNetwork"
case "productCode" -> "globalProductCode"
case "productName" -> "globalProductDescription"
else -> ""
}) filter ($ != "") distinctBy ($) joinBy ","
output application/json
---
{
"columnList": fromStringSourceFieldToTargetFields(payload.columnList)
}
DataWeave Output:
Output:
{
"columnList":
"merchantNameLocation,merchantNetwork,globalProductCode,globalProductDescription"
}
Conclusion
It's easy to learn the below commonly used DataWeave functions, to solve day-to-day integration mapping requirements.
For more details, find the below MuleSoft Developer Documentation.
lower | map | splitBy | If else | trim | distinctBy | filter | camelize | joinBy | match | fun | DataWeave Language
Happy Learning ...!
Vikas Kerehalli
Good one
Awesome!