You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:无法获取API返回对象中各加密货币的USD数值

Solution: Extracting Cryptocurrency USD Prices from API Response

Hey there! Let's get this sorted for you. The core issue here is that request.responseText returns a JSON string, not a native JavaScript object. You can't directly access nested properties like XRP.USD on a string—so we need to parse it first. Here's how to do it step by step:

Step 1: Parse the JSON String into a JavaScript Object

First, convert the raw response text into a workable JS object using JSON.parse():

// Your existing response text stored in XRPUSD
let XRPUSD = '{"XRP":{"USD":1.08},"ETH":{"USD":921.49},"BTC":{"USD":11755.04}}';

// Parse the string to an object
const priceData = JSON.parse(XRPUSD);

Step 2: Extract Individual USD Prices

Now you can access each cryptocurrency's USD value using dot notation (or bracket notation if you prefer):

// Extract XRP's USD price
const xrpUsd = priceData.XRP.USD;
// Or using bracket notation: priceData['XRP']['USD']

// Extract ETH's USD price
const ethUsd = priceData.ETH.USD;

// Extract BTC's USD price
const btcUsd = priceData.BTC.USD;

Step 3: Verify the Results

Test it out with console.log to confirm you're getting the right values:

console.log("XRP Price (USD):", xrpUsd); // Output: 1.08
console.log("ETH Price (USD):", ethUsd); // Output: 921.49
console.log("BTC Price (USD):", btcUsd); // Output: 11755.04

Bonus: Simplify with Modern Fetch API

If you're using the modern fetch API instead of an older XMLHttpRequest, you can skip manual parsing entirely by using the .json() method, which automatically converts the response to a JS object:

fetch('https://min-api.cryptocompare.com/data/pricemulti?fsyms=XRP,ETH,BTC&tsyms=USD')
  .then(response => response.json())
  .then(priceData => {
    console.log("XRP:", priceData.XRP.USD);
    console.log("ETH:", priceData.ETH.USD);
    console.log("BTC:", priceData.BTC.USD);
  })
  .catch(error => console.error("Failed to fetch data:", error));

That should resolve your issue—you'll be able to access each cryptocurrency's USD value without any problems now.

内容的提问来源于stack exchange,提问作者Andrew Lee

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:19:27