为了账号安全,请及时绑定邮箱和手机立即绑定

从websocket过滤json对象/值并打印到控制台日志

从websocket过滤json对象/值并打印到控制台日志

慕桂英546537 2021-05-01 10:07:39
尝试打印到控制台日志从websocket提供的json数据中获取一个值下面的代码将所有的json数据从websocket打印到控制台日志。// require wsconst WebSocket = require('ws');//messsage sent to  ws servervar msg =     {"jsonrpc": "2.0",     "method": "public/subscribe",     "id": 42,     "params": {        "channels": ["price_index.btc_usd"]}    };// WS connection urlvar ws = new WebSocket('wss://website.com/ws/api/v2');//ws responsews.onmessage = function (e) {    // do something with the notifications...    console.log('server : ', e.data);};//stringify json dataws.onopen = function () {    ws.send(JSON.stringify(msg));};预期结果:server :  5457.21server :  5457.19server :  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"}}}
查看完整描述

2 回答

?
翻翻过去那场雪

TA贡献2065条经验 获得超14个赞

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 {}


查看完整回答
反对 回复 2021-05-13
?
绝地无双

TA贡献1946条经验 获得超4个赞

您正在登录所有内容e.data

从实际结果json,看起来像你想要的 e.data.params.data.price

正如Robofan所说,您需要先对其进行解析。

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


查看完整回答
反对 回复 2021-05-13
  • 2 回答
  • 0 关注
  • 250 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信