JavaScript JSON parser that reports an error

I am having trouble parsing the JSON received using WebSocket (the original question is Parse JSON received with WebSocket results with an error ). The JSON string itself is valid (verified by several JSON checks), but JSON.parse throws an exception. I am trying to figure out what it is that it cannot parse, but the only thing I get is "SyntaxError: unexpected_token ILLEGAL", it does not say where the exact position of the failed token is. Is there any way to extract such information?

Refresh . If I copy this JSON string to a static file (for example, "data.json"), then extract it and parse it using the same function (JSON.parse) - then it works fine. Therefore, I suppose that something tricky is happening, I was thinking about a newline character (maybe it was \ n instead of \ r \ n or vice versa), but completely removing all line breaks did not help. I would think that this might very well be a coding problem, but the data is received through websocket and, according to the documentation, this is utf-8 string.

2nd Update : IT WORKS is great if I use "json_parse" here: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js Then it works great! Does this mean that this is a bug in the implementation of "JSON.parse" used by Chrome or what?

Thanks.

+4
source share
4 answers

You can copy the JSON.parse () implementation from somewhere (for example, from jQuery), change its name so that you can call it directly, configure the implementation so that it never detects the built-in parser, so it always uses the JS analyzer, and then change your code to use the new JS version of the parser, and then pass through it in the javascript debugger until you find what he doesn't like.

+3
source

I think you do not need to call JSON.parse:

JSON.parse({"key": "whatever"}) // Syntax Error ILLEGAL 

because it is already an object. I would also be interested to see the result of the following code:

 eval("(" + json + ")"); 

Or

 JSON.parse(decodeURIComponent(json)); 
+1
source

You can check if you have quotes and slashes in the JSON string. If yes, they should be escaped:

 { "key": "i've \"quotes\" in me", "key2": "and \\slashes too" } 

In addition, JSONLint gives the exact location of the error.

According to JSON.org, you cannot have quotation marks and slashes in your lines, so you need to avoid them.

enter image description here

+1
source

It is not possible to talk in detail about the details, but it is possible that your validator does a lax parsing and your javascript can do a strict parsing ...

0
source

All Articles