从websocket过滤json对象/值并打印到控制台日志
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从websocket过滤json对象/值并打印到控制台日志相关的知识,希望对你有一定的参考价值。
尝试打印到控制台记录websocket提供的json数据中的值
下面的代码将所有json数据从websocket打印到控制台日志。
// require ws
const WebSocket = require('ws');
//messsage sent to ws server
var msg =
{"jsonrpc": "2.0",
"method": "public/subscribe",
"id": 42,
"params": {
"channels": ["deribit_price_index.btc_usd"]}
};
// WS connection url
var ws = new WebSocket('wss://test.deribit.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);
以上是关于从websocket过滤json对象/值并打印到控制台日志的主要内容,如果未能解决你的问题,请参考以下文章
通过 Websocket 控制器打印从 Stomp 传入的 json 数组