3

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.

Infinity
  • 484
  • 2
  • 8
  • 21

1 Answers1

5

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"
    }
  ]
]
machaval
  • 4,969
  • 14
  • 20