gpt4 book ai didi

node.js - 从 Node.js 中的 websocket 数据源读取 JSON 数组

转载 作者:太空宇宙 更新时间:2023-11-04 00:29:54 24 4
gpt4 key购买 nike

我是 javascript 和编码的初学者。我想做的是从这个 websocket 数据源获取出价(数组),但我很挣扎,在我的代码中我尝试仅打印(console.log)“bidPrice”而不是其他所有内容,例如“询问大小”、“出价大小”等当我运行我的代码时,我只得到未定义的结果,而不是“bidPrice”,这里缺少什么?感谢您的帮助

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

C:\Users\Desktop\codesource>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:\Users\jalal\Desktop\codesource\wss.js:24
console.log(response.data[0].bidPrice);
^

TypeError: Cannot read property '0' of undefined
at WebSocket.<anonymous> (C:\Users\jalal\Desktop\codesource\wss.js:24:27)
at emitTwo (events.js:106:13)
at WebSocket.emit (events.js:191:7)
at Receiver.ontext (C:\Users\jalal\Desktop\codesource\node_modules\ws\lib\WebSocket.js:841:10)

最佳答案

改变

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

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

仅供引用,您不需要变量 datajson

关于node.js - 从 Node.js 中的 websocket 数据源读取 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41371021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com