从 WebSocket 筛选 JSON 对象/值并打印到控制台日志



尝试从 websocket 提供的 json 数据中打印到控制台日志

的值

下面的代码将 websocket 中的所有 json 数据打印到控制台日志中。

// require ws
const WebSocket = require('ws');

//messsage sent to  ws server
var msg = 
    {"jsonrpc": "2.0",
     "method": "public/subscribe",
     "id": 42,
     "params": {
        "channels": ["price_index.btc_usd"]}
    };
// WS connection url
var ws = new WebSocket('wss://website.com/ws/api/v2');
//ws response
ws.onmessage = function (e) {
    // do something with the notifications...
    console.log('server : ', e.data);
};
//stringify json data
ws.onopen = function () {
    ws.send(JSON.stringify(msg));
};

预期成果:

server :  5457.21
server :  5457.19
server :  5457.15

实际结果:

server :  {"jsonrpc":"2.0","method":"subscription","params":{"channel":"deribit_price_index.btc_usd","data":{"timestamp":1556209117657,"price":5457.21,"index_name":"btc_usd"}}}
server :  {"jsonrpc":"2.0","method":"subscription","params":{"channel":"deribit_price_index.btc_usd","data":{"timestamp":1556209117657,"price":5457.19,"index_name":"btc_usd"}}}

JSON.parse()

这是您可以使用它的方式:

    //This will turn it into an object you can navigate with '.params.data.price'
    try {
        console.log('server: ', JSON.parse(e.data).params.data.price);
    } catch {}

您正在e.data中记录所有内容。

从实际结果 json 来看,您似乎想要e.data.params.data.price

正如Robofan所说,你需要先解析它。

console.log('server : ', e.data); -> console.log('server : ', JSON.parse(e).params.data.price);

最新更新