Strange JSON.parse () error in node.js

I am extracting some compressed JSON over TCP in node.js to parse them. So my approach is similar to this. I shorten and simplify it, so you do not need to know the surrounding logic.

socket.on("data", function(data) { console.log(data.toString()); // Shows the original stringifyed version console.log(JSON.parse(data.toString())); // Doesn't work }); 

Full (decorated) JSON is this. As you can see, there are no errors.

 { "result": "success", "source": "chat", "success": { "message": "test", "time": 1331770513, "player": "silvinci" } } 

But JSON.parse(data.toString()) always throws me this dumb error:

 {"result":"success","source":"console","success":{"time":1331762264,"line":"20 ^ SyntaxError: Unexpected token { at Object.parse (native) at Socket.<anonymous> (/home/node/api.js:152:35) // irrelevant from here on at Socket.emit (events.js:67:17) at TCP.onread (net.js:347:14) 

So I ask: "What could be wrong with JSON-String. Try it directly, should not work." Surprise Surprise! It worked. Why does this work when I directly enter a string?

+4
source share
2 answers

Thanks @ Felix Kling I found my mistake. It is very important to filter unescaped characters, especially outside of string JSON. I did not miss and did not notice the invisible ruler immediately after the string JSON.

This fix is:

 socket.on("data", function(data) { console.log(data.toString()); // Shows the original stringified version console.log(JSON.parse(data.toString().slice(0, -4))); // Trim the sequence "\r\n" off the end of the string }); 

Please note that this only works for me, as I have a very specialized case. The server always responds in JSON strings that end with \r\n - not whitespace, but literally the backslash r and the backslash n.
Your code may (or probably) fail due to other errors. But checking the server response is a good starting point when you get parsing errors.

As pointed out by @ Zack , this is a more general solution for removing unintentional spaces:

 JSON.parse(data.toString().trim()); 
+12
source

I had a similar problem. For a more general solution, this will work too. It removes all spaces before and after the line, so you do not need to do a specific length of the substring.

 JSON.parse(data.trim()); 
+2
source

Source: https://habr.com/ru/post/1401507/


All Articles