Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lookup Country Code from the phone Numbers using Dataweave Mule

Tags:

mule

dataweave

My Input Request JSON looks like this below:

{
    "phoneNumbers": [{
        "phoneNumberType": "mobile",
        "phoneNumber": "54112724555"
    },
    {
        "phoneNumberType": "mobile",
        "phoneNumber": "16298765432"
    }
    ]
}

I want to generate Output Json Like this :

{
    "phoneNumbers": [{
        "phoneNumberType": "mobile",
        "phoneNumber": "54112724555",
        "CountryCode": "ARG"
    },
    {
        "phoneNumberType": "mobile",
        "phoneNumber": "16298765432",
        "CountryCode": "US"
    }
    ]
}

I derive the countryCode from the PhoneNumber using callingCode and CountryCode Mapping given in csv file.

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
.,.
.,.

I have used the fileConnector to read the CSV File and stored it in Vars.CallingCodeMapping.

I have to do lookup phoneNumber with calling code by passing first letter from the phonenumber matching return countryCode then first two letter ....firstsixLetter if nothing matches return NA.

like image 920
Infinity Avatar asked Jan 21 '26 03:01

Infinity


1 Answers

Given this input as payload

[
   "54112724555",
   "16298765432"
]

And this csv in a var called country_codes

%dw 2.0
output application/json

var codeByCode = vars.country_code groupBy ((item, index) -> item.CALLING_CODE)
/**
* Returns the Country code or Null if not found
*/
fun lookupCountrCode(phoneNumber:String): String | Null = 
    //map the each sub part to a country code or null
    (0 to 6 map ((index) ->  codeByCode[phoneNumber[0 to index]]) 
            //Filter non null and take the first this will return null if array is empty
            filter ((item, index) -> item != null))[0]

---
payload map ((item, index) -> lookupCountrCode(item))

Outputs

[
  [
    {
      "CALLING_CODE": "54",
      "COUNTRY_CODE": "ARG"
    }
  ],
  [
    {
      "CALLING_CODE": "1",
      "COUNTRY_CODE": "US"
    }
  ]
]
like image 150
machaval Avatar answered Jan 22 '26 20:01

machaval



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!