1

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:

enter image description here

salocinx
  • 3,715
  • 8
  • 61
  • 110
  • Change the `console.log()` to `console.log(typeof e.data);` – Pointy Nov 16 '17 at 14:53
  • Thanks for quick response. I get `string` as a result. So what could be the problem? – salocinx Nov 16 '17 at 15:01
  • 3
    how does the response look in your Network tab? the token mentioned is a space. must be an encoding issue – Radu Chiriac Nov 16 '17 at 15:07
  • What is the char code at position 60 of the data? – Bergi Nov 16 '17 at 15:15
  • My server app is running on a ESP8266 and the JSON string are sent from there with a fixed size of 128 bytes. Probably the padding makes problems. I will update my initial question with a link to a screenshot. – salocinx Nov 16 '17 at 15:26
  • there you go, you need to trim that somehow. try `e.data.trim()` although not really the function's purpose, then check this https://stackoverflow.com/questions/24229262/match-non-printable-non-ascii-characters-and-remove-from-text – Radu Chiriac Nov 16 '17 at 16:08
  • Yes indeed, the padded values messed the string up. I already tried `trim()`? but didn't remove the redundant characters (somehow not recognized as spaces). However, `e.data.substring(0, e.data.lastIndexOf("}")+1)` did the job. Thank you very much for your help! – salocinx Nov 16 '17 at 16:41

0 Answers0