如何动态获取CoinGecko API返回JSON中随URL变化的加密货币价格
动态获取CoinGecko Simple Price API返回价格的解决方案
核心逻辑:你发起请求时已经明确传入crypto(加密货币标识)和currency(法币标识)两个参数,直接用这两个变量作为键名访问返回的JSON结构即可,无需硬编码固定键名。
常用语言实现示例
JavaScript
// 请求参数 const crypto = 'bitcoin'; const currency = 'aud'; // 发起请求获取返回JSON const res = await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${crypto}&vs_currencies=${currency}`).then(r => r.json()); // 动态取值 const price = res[crypto][currency]; console.log(price); // 示例输出:44768
Python
import requests # 请求参数 crypto = 'bitcoin' currency = 'aud' # 发起请求获取返回JSON response = requests.get(f"https://api.coingecko.com/api/v3/simple/price?ids={crypto}&vs_currencies={currency}") res_json = response.json() # 动态取值 price = res_json[crypto][currency] print(price) # 示例输出:44768
兼容处理建议
如果需要避免参数错误、币种不存在导致的报错,可以加非空校验:
- JavaScript 可选链写法:
const price = res?.[crypto]?.[currency] - Python 字典get方法写法:
price = res_json.get(crypto, {}).get(currency)
如果需要同时请求多个加密货币/多个法币,遍历你传入的参数数组取值即可:
const cryptos = ['bitcoin', 'ethereum', 'solana']; const currency = 'aud'; const res = await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${cryptos.join(',')}&vs_currencies=${currency}`).then(r => r.json()); const priceResult = {}; cryptos.forEach(item => { priceResult[item] = res[item]?.[currency] || null; })
内容的提问来源于stack exchange,提问作者Lachlan Kemp
相关产品推荐
相关产品推荐

