从node.js中读取websocket数据feed的JSON数组



我是JavaScript和编码的初学者。我要做的是从此WebSocket数据提要中获取出价价格(数组),但我正在努力,在我的代码中,我尝试打印(console.log)仅" bidprice",而不是其他所有类似的东西"询问","竞标"等等当我运行代码时,我只会得到未定义的,而不是" BIDPRICE",这里缺少什么?谢谢您的任何帮助

在这里,当我运行代码不好时,结果(cmd)!!!!

C:UsersDesktopcodesource>node wss.js
Connection opened
undefined
undefined
undefined

这是我在node.js中的代码:

fs = require('fs');
var WebSocket = require('ws');
var ws = new WebSocket('wss://www.bitmex.com/realtime');
ws.on('open', function() {
    console.log('Connection opened');
    //out
    ws.send(JSON.stringify({"op": "subscribe", "args": ["quote:XBTUSD"]}));

});
//in            
ws.on('message',function(message){var response = JSON.parse(message) 
 fs.writeFile('helloworld.txt', JSON.stringify(message));
 fs.writeFile('helloworld.json', JSON.stringify(message));

    var data = message;
    var json = JSON.parse(data);
    console.log(json["bidPrice"]);
});

这是来自Bitmex WebSocket

的数据
Connection opened
{ info: 'Welcome to the BitMEX Realtime API.',enter code here
  version: '1.2.0',
  timestamp: '2016-12-28T22:27:15.000Z',
  docs: 'https://www.bitmex.com/app/wsAPI',
  heartbeatEnabled: false }
{ success: true,
  subscribe: 'quote:XBTUSD',
  request: { op: 'subscribe', args: [ 'quote:XBTUSD' ] } }
{ table: 'quote',
  keys: [],
  types:
   { timestamp: 'timestamp',
     symbol: 'symbol',
     bidSize: 'long',
     bidPrice: 'float',
     askPrice: 'float',
     askSize: 'long' },
  foreignKeys: { symbol: 'instrument' },
  attributes: { timestamp: 'sorted', symbol: 'grouped' },
  action: 'partial',
  data:
   [ { timestamp: '2016-12-28T22:26:54.645Z',
       symbol: 'XBTUSD',
       bidSize: 12,
       bidPrice: 969.59,
       askPrice: 971.06,
       askSize: 499 } ] }

看来它不起作用

console.log(response.data[0].bidPrice);

Connection opened
C:UsersjalalDesktopcodesourcewss.js:24
        console.log(response.data[0].bidPrice);
                                 ^
TypeError: Cannot read property '0' of undefined
    at WebSocket.<anonymous> (C:UsersjalalDesktopcodesourcewss.js:24:27)
    at emitTwo (events.js:106:13)
    at WebSocket.emit (events.js:191:7)
    at Receiver.ontext (C:UsersjalalDesktopcodesourcenode_moduleswslibWebSocket.js:841:10)

更改

console.log(json["bidPrice"]);

to

console.log(response.data[0].bidPrice);

fyi您不需要变量datajson

最新更新