You need to enable JavaScript to run this app. 如何动态获取CoinGecko API返回JSON中随URL变化的加密货币价格
优惠活动
大模型
产品
解决方案
定价
更多

如何动态获取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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 19:54:08