Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert evt.data from websocket to jSON string or plain string in Javascript

Recently I played with websocket and it works great,

in the client side with onmessage(evt) function, I received a message from the server side, the message is actually a JSON format like this:

{"Properties":{"name":"0a67d327-1f78-475e-b58a-d16706782223","publicname":"Page1"}}

then in the client side(html5 with javascript) I access the data using:

var page=evt.data;

then I access the JSON object

document.getElementById('name').innerHTML=page.Properties.name;

but it just won't work, I even use the eval function but it still doesn't work, I did check the page by using alert(page);

I wonder if the evt.data is not a string data but a byte, anyone have a solution for converting byte to string? or any other solution that may have something to do with this evt.data

like image 976
Eldon Lesley Avatar asked Feb 19 '26 19:02

Eldon Lesley


1 Answers

WebSocket data is either string, Blob, or ArrayBuffer. In your case it is most likely a string so you need to parse it first:

var page = JSON.parse(evt.data);
console.log("Properties.name: " + page.Properties.name);
like image 159
kanaka Avatar answered Feb 22 '26 08:02

kanaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!