javascript - 从 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 {}
推荐阅读
- google-sheets - 使用 sum 和 countifs 按月和团队在多个列中获得“是”的百分比 - 有没有更简单的方法?
- django - 使用 self.add_error() 和引发 ValidationError() 有什么区别?
- excel - 尝试使用 C# Windows 应用程序将公式添加到 Excel 输出中的列。但是得到#NAME?错误
- python - Multicell LSTM RNN 返回 nan 训练错误
- python - 通过使用二维数组索引来填充 numpy 数组
- r - 在使用 AFINN 词典的 inner_join() 之后,单词列表如何仍然具有比词典更多的元素?
- android-studio - Android Studio 不显示颤振设备
- docusignapi - DocuSign - 本机应用程序中的嵌入式签名
- html - 如何 W3C 验证 React 应用程序 HTML 输出
- c# - C# windows窗体中的scanf?