I am currently struggling with a JSON string that I receive from my server application.
This is the JavaScript snippet that receives the JSON string:
var connection = new WebSocket('ws://'+location.hostname+':81/', ['arduino']);
connection.onmessage = function (e) {
console.log('Received from server: ', e.data);
var response = JSON.parse(e.data);
if(response.action=="networks") {
console.log('SSID: ', response.ssid);
}
};
I get this response in my browser's console according to my console.log
call above:
Received from server: {"action":"networks","ssid":"UPC6288862","rssi":-69,"enc":8}
Ending in the following error:
Uncaught SyntaxError: Unexpected token in JSON at position 60
at JSON.parse (<anonymous>)
at WebSocket.connection.onmessage (WebSocket.js:19)
connection.onmessage@WebSocket.js:19
When I manually put the string, to JSON.parse() like this:
var data = JSON.parse('{"action":"networks","ssid":"UPC Wi-Free","rssi":-42,"enc":255}');
the parsing works and I can access the fields by response.action
for example.
But why I get the error? Is e.data
not a proper string or do I need to add some quotes or similar to e.data
before parsing?
UPDATE:
Here's a screenshot of Chrome's network tab while receiving the JSON string via the WebSocket.js: