javascript - 从 Binance API 获取数据到 Javascript 数组
问题描述
我刚开始使用 API,对如何将收到的数据传输到 JavaScript 数组有些困惑。我有这段代码从 Binance API 接收数据并在控制台中显示。
var burl ='https://api.binance.com';
var query ='/api/v3/klines';
query += '?symbol=BTCUSDT&interval=15m&limit=2';
var url = burl + query;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.onload = function(){
console.log(ourRequest.responseText);
}
ourRequest.send();
我还有一个来自 FusionCharts Library 的硬脚本图表。图表的源代码在这里 - FusionChart Candlestick Chart
const dataSource = {
chart: {
caption: "Bitcoin Price",
subcaption: "Q4-2017",
numberprefix: "$",
pyaxisname: "Price (USD)",
showvolumechart: "1",
vnumberprefix: "$",
vyaxisname: "Volume traded",
exportenabled: 1,
theme: loadedTheme || ThemeAliases.light
},
categories: [
{
category: [
{
label: "Jan",
x: "1"
},
{
label: "Feb",
x: "32"
},
{
label: "Mar",
x: "62"
},
{
label:"Apr",
x:"12"
}
]
}
],
dataset: [
{
data: [
{
tooltext:
"<b>Oct 01, 2017</b><br>Open: <b>$openDataValue</b><br>Close: <b>$closeDataValue</b><br>High: <b>$highDataValue</b><br>Low: <b>$lowDataValue</b><br>Volume: <b>$volumeDataValue</b>",
open: 4341.05,
high: 4403.74,
low: 4269.81,
close: 4403.74,
volume: 1208210000,
x: 1
},
FusionCharts.ready(function() {
var myChart = new FusionCharts({
type: "candlestick",
renderAt: "chart-container",
width: "75%",
height: "100%",
dataFormat: "json",
dataSource
}).render();
});
解决方案
结果ourRequest.responseText
作为字符串返回,而不是数组。要修复它,只需使用该JSON.parse
方法。您还将它存储在一个变量中,例如:
var burl ='https://api.binance.com';
var query ='/api/v3/klines';
query += '?symbol=BTCUSDT&interval=15m&limit=2';
var url = burl + query;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.onload = function(){
// Will convert the string to something Javascript can understand
var result = JSON.parse(ourRequest.responseText);
// You can now use it as an array
console.log(result);
}
ourRequest.send();
这能回答问题吗?
推荐阅读
- javascript - 有没有办法自定义css过渡?
- python - 如果我知道它在 python 中的编号,我可以在文本文件中找到一行吗?
- typescript - Typescript next.js + i18n 的正确 getServerSideProps 语法
- javascript - 使用react js和express js时获取请求不起作用,未处理的拒绝(TypeError):无法获取
- javascript - 迭代每个 forEach 迭代中的剩余元素
- postgresql - PostgresSQL - 只能访问视图的用户
- maven - Intellij Log4j 核心依赖项下载失败
- performance - 步进负载在最后一个蝗虫版本 (2.4.3) 中有效吗?
- ecmascript-6 - CasperJS 和 PhantomJS 意外令牌'const'
- java - 背压不适用于 groupBy 运算符