首页 > 解决方案 > 使用 Dataweave Mule 从电话号码中查找国家代码

问题描述

我的输入请求 JSON 如下所示:

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

我想像这样生成输出Json:

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

我使用 csv 文件中给出的 callCode 和 CountryCode 映射从 PhoneNumber 派生 countryCode。

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

我已使用 fileConnector 读取 CSV 文件并将其存储在 Vars.CallingCodeMapping 中。

我必须通过从匹配返回 countryCode 的电话号码中传递第一个字母然后传递前两个字母 ....firstsixLetter 来查找电话号码和呼叫代码,如果没有匹配返回 NA。

标签: muledataweave

解决方案


将此输入作为有效负载

[
   "54112724555",
   "16298765432"
]

而这个 csv 在一个名为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))

输出

[
  [
    {
      "CALLING_CODE": "54",
      "COUNTRY_CODE": "ARG"
    }
  ],
  [
    {
      "CALLING_CODE": "1",
      "COUNTRY_CODE": "US"
    }
  ]
]

推荐阅读