Search code examples
javascriptjsonobjectwebsocketbinance

JSON object values cannot be accessed using key names in JS


i am trying to get data from Binance web sockets in my react app

const ws = new WebSocket("wss://stream.binance.com:9443/ws/ethbtc@trade");
ws.onopen = () => {
  ws.send(
    JSON.stringify({
      method: "SUBSCRIBE",
      params: ["ethbtc@trade"],
      id: 13
    })
  );
};
ws.onmessage = evnt => {
  console.log(evnt.data);
};

and the response is {"e":"trade","E":1593865856744,"s":"ETHBTC","t":180904813,"p":"0.02493100","q":"0.90600000","b":788853315,"a":788853661,"T":1593865856743,"m":true,"M":true}

but when trying to get a specific value from the above object it shows undefined !

console.log(evnt.data.s)

it shows undefined

if anyone can help it will be great, Thanks in advance!


Solution

  • please try like this

    1. console.log(evnt.data["s"]) Or,
    2. console.log(JSON.parse(evnt.data).s) Or,
    3. console.log(evnt.data.toObject().s)