首页 > 解决方案 > 从 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();
});

标签: javascriptjsonapiget

解决方案


结果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();

这能回答问题吗?


推荐阅读