Contact Us 1-800-596-4880

Look Up Data in a CSV File

This DataWeave example uses filter with map to look up data in a CSV file and return a country code for each calling code found within an input array of phone numbers. Before you begin, note that DataWeave version 2 (%dw 2.0) is for Mule 4 apps. For a Mule 3 app, refer to DataWeave version 1 (%dw 1.0) examples, within the Mule 3.9 documentation set. For other Mule versions, you can use the Mule Runtime version selector in the table of contents.

The following JSON payload provides an array of phone numbers to the DataWeave script.

[
   "54-112724555",
   "1-6298765432"
]

The value of the Mule variable country_codes is a CSV file that maps calling codes to country codes.

CALLING_CODE,COUNTRY_CODE
1,US
7,RU
54,AR
20,EG
32,BE
33,FR
505,NI
506,CR
1876,JM
1905,CA
1939,PR
262262,RE
262269,YT
.,.
.,.

The following DataWeave script reads each phone number in the payload and uses the filter function to search for the calling code within the Mule variable country_code that matches the calling code in the phone number. Then the map function gets the country code that corresponds to the calling code and returns the results to an array of JSON objects.

DataWeave Script:
%dw 2.0
output application/json

fun lookupCountryCode(phoneNumber: String): String = do {
    var callingCode = (phoneNumber splitBy("-"))[0]
    ---
    (vars.country_code filter ((item, index) -> item.CALLING_CODE == callingCode) map ((item, index) -> item.COUNTRY_CODE))[0]
}
---
payload map ((item, index) -> { phone: item, countryCode: lookupCountryCode(item)})
Sample Output (JSON):
[
  {
    "phone": "54-112724555",
    "countryCode": "AR"
  },
  {
    "phone": "1-6298765432",
    "countryCode": "US"
  }
]