Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript JSON parser that tells error position

I've been having some troubles with parsing JSON that is received with WebSocket (original question - Parse JSON received with WebSocket results in error). The JSON string itself is valid (tested with several JSON validators), but JSON.parse throws an exception. I am trying to figure out what is it exactly that it cannot parse, but the only thing I'm getting is "SyntaxError: unexpected_token ILLEGAL", it doesn't say where is the exact position of the failed token. Is there any way of extracting such information?

Update: If I copy-paste that JSON string to a static file (e.g. "data.json") and then retrieve it and parse it with the same function (JSON.parse) - then it works fine. So I'm assuming there's something tricky going on, I thought of newline symbol (may be there was \n instead of \r\n or vice versa) but completely removing all the line breaks didn't help. I would think that it very well may be an encoding problem, but the data is received via websocket and according to documentation it's utf-8 string.

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

Thank you.

like image 304
stepan Avatar asked Aug 19 '11 15:08

stepan


2 Answers

You could copy an implementation of JSON.parse() from somewhere (like out of jQuery), change it's name so you can call it directly, tweak the implementation so that it never detects the built-in parser so it always uses the JS parser and then change your code to use the new JS version of the parser, then trace through it in a javascript debugger until you find what it doesn't like.

like image 76
jfriend00 Avatar answered Oct 01 '22 01:10

jfriend00


One thing to check is if you have quotes and slashes within your JSON string. If yes, they need to be escaped:

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

Also, JSONLint gives you the exact location of the error.

As per JSON.org, you cannot have quotes and slashes in your strings, so you need to escape them.

enter image description here

like image 25
Mrchief Avatar answered Oct 01 '22 03:10

Mrchief