无法解析nodejs中api中的JSON数据

Can't parse JSON data from api in nodejs

本文关键字:api 中的 JSON 数据 nodejs      更新时间:2023-09-26

我正在努力使这个工作,但我不知道为什么它不工作。

//require the poloniex library
var plnx;
var currenciesJSON;
if (plnx = require('plnx')){
  console.log("Poloniex library intialized.");
}
//
a = 0;
setInterval(function() { intervalFunction() }, 1000);
function intervalFunction(){
  plnx.returnCurrencies({}, function(err, data) {
    currenciesJSON = data;
    console.log(err);
    console.log(currenciesJSON);
  });
  var currenciesOBJ = JSON.parse(currenciesJSON);
  a++;
  console.log("Check #"+a+" complete.");
}

我得到以下错误:

[nodemon] starting `node main.js`
Poloniex library intialized.
undefined:1
undefined
^
SyntaxError: Unexpected token u
at Object.parse (native)
at intervalFunction (E:'CODING'nodejs'main.js:22:28)
at null.<anonymous> (E:'CODING'nodejs'main.js:10:26)
at wrapper [as _onTimeout] (timers.js:265:14)
at Timer.listOnTimeout (timers.js:110:15)
[nodemon] app crashed - waiting for file changes before starting...

您正在尝试在分配变量之前解析它的值。plnx.returnCurrencies()是异步的,所以

var currenciesOBJ = JSON.parse(currenciesJSON)

将(最初)等同于

var currenciesOBJ = JSON.parse(undefined)

将等价于(由于类型强制转换)

var currenciesOBJ = JSON.parse('undefined')

因此关于字符'u'

的SyntaxError错误

这可能只是一个问题,直到plnx.returnCurrencies()回调被调用至少一次,因为currenciesJSON将被定义。