如何在JavaScript中根据两位国家代码获取三位货币与国家代码
解决方案:通过两位国家代码获取三位货币/国家代码
1. Python 环境:使用 pycountry 库
pycountry 是基于ISO标准维护的工具库,包含完整的国家、货币等标准化数据,完全匹配你的需求。
安装命令:
pip install pycountry
示例代码:
import pycountry def get_currency_and_country(alpha2_code): try: # 匹配两位国家代码(自动转大写兼容小写输入) country = pycountry.countries.get(alpha_2=alpha2_code.upper()) if not country: return None, None # 提取三位国家代码 alpha3_country = country.alpha_3 # 提取对应货币的三位代码 currency = pycountry.currencies.get(numeric=country.numeric) alpha3_currency = currency.alpha_3 if currency else None return alpha3_currency, alpha3_country except: return None, None # 测试示例 print(get_currency_and_country("us")) # 输出 ('USD', 'USA') print(get_currency_and_country("in")) # 输出 ('INR', 'IND')
2. JavaScript/Node.js 环境:使用 country-data 库
country-data 同样基于ISO标准,适合前端或Node.js场景使用。
安装命令:
npm install country-data
示例代码:
const { countries, currencies } = require('country-data'); function getCurrencyAndCountry(alpha2Code) { const targetCountry = countries.all.find(c => c.alpha2 === alpha2Code.toUpperCase()); if (!targetCountry) return [null, null]; const alpha3Country = targetCountry.alpha3; const targetCurrency = currencies.all.find(c => c.code === targetCountry.currency); const alpha3Currency = targetCurrency ? targetCurrency.code : null; return [alpha3Currency, alpha3Country]; } // 测试示例 console.log(getCurrencyAndCountry("us")); // 输出 ['USD', 'USA'] console.log(getCurrencyAndCountry("in")); // 输出 ['INR', 'IND']
3. 轻量方案:自定义映射表
如果不想引入第三方依赖,可手动维护一个精简的映射字典,适合国家范围有限的场景:
{ "us": {"currency": "USD", "country_code": "USA"}, "in": {"currency": "INR", "country_code": "IND"}, // 按需添加其他国家数据 }
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

