求助:如何将API返回的多维数组JSON数据在HTML表格中展示
解决CoinGecko API多维数组数据渲染到HTML表格的问题
我来帮你搞定这个数据渲染的问题!咱们先拆解核心问题,再一步步修正代码:
核心问题分析
你在show函数里尝试遍历data.list,但CoinGecko返回的API数据里根本没有list这个属性!返回的对象直接包含三个顶级数组:prices、market_caps、total_volumes,而且这三个数组的长度完全一致(都是471条),每条数据都是[时间戳, 数值]的格式。
另外,直接渲染原始的时间戳和数组格式也不友好,咱们需要把时间戳转换成可读的日期时间,同时提取出每个数组里的数值来展示。
修正后的完整代码
JavaScript代码
// api url const api_url = "https://api.coingecko.com/api/v3/coins/comfytoken/market_chart?vs_currency=usd&days=30&interval=minutely"; // Defining async function async function getapi(url) { // Storing response const response = await fetch(url); // Storing data in form of JSON var data = await response.json(); console.log(data); if (response) { hideloader(); } show(data); } // Calling that async function getapi(api_url); // Function to hide the loader function hideloader() { document.getElementById('loading').style.display = 'none'; } // 辅助函数:把时间戳转成可读日期时间 function formatTimestamp(timestamp) { const date = new Date(timestamp); return date.toLocaleString(); // 可根据需求调整格式,比如toLocaleDateTimeString() } // Function to define innerHTML for HTML table function show(data) { let tab = `<tr> <th>时间</th> <th>价格(USD)</th> <th>市值(USD)</th> <th>交易量(USD)</th> </tr>`; // 遍历三个数组的索引(因为长度一致) for (let i = 0; i < data.prices.length; i++) { // 取出对应位置的三条数据 const priceItem = data.prices[i]; const marketCapItem = data.market_caps[i]; const volumeItem = data.total_volumes[i]; // 格式化时间和数值 const time = formatTimestamp(priceItem[0]); const price = priceItem[1].toFixed(2); // 保留两位小数 const marketCap = marketCapItem[1].toLocaleString(); // 添加千分位分隔符 const volume = volumeItem[1].toLocaleString(); tab += `<tr> <td>${time}</td> <td>$${price}</td> <td>$${marketCap}</td> <td>$${volume}</td> </tr>`; } // Setting innerHTML as tab variable document.getElementById("employees").innerHTML = tab; }
HTML代码(微调表头和样式提示)
<html lang="en"> <head> <script src="script.js"></script> <style> /* 给表格加基础样式,方便阅读 */ table { border-collapse: collapse; width: 100%; margin-top: 20px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } </style> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>CoinGecko Market Data</title> </head> <body> <!-- Loader --> <div class="d-flex justify-content-center"> <div class="spinner-border" role="status" id="loading"> <span class="sr-only">Loading...</span> </div> </div> <h1>ComfyToken 30分钟级市场数据</h1> <!-- Table for showing data --> <table id="employees"></table> </body> </html>
关键修改点说明
- 移除错误的
data.list遍历:改成按索引遍历prices数组(因为三个数组长度一致),同时获取对应位置的market_caps和total_volumes数据。 - 新增时间戳格式化函数:把原始的毫秒时间戳转换成人类可读的日期时间字符串。
- 数值格式化:给价格保留两位小数,给市值和交易量添加千分位分隔符,让数据更易读。
- 优化表头:把原来的模糊表头改成更清晰的名称,增加了“时间”列。
- 添加基础表格样式:避免表格杂乱,提升可读性。
这样修改后,就能正确从API提取数据并渲染成美观的HTML表格了!
内容的提问来源于stack exchange,提问作者Shikhar
相关产品推荐
相关产品推荐

