stepan
stepan

Reputation: 1105

Parse JSON received with WebSocket results in error

I have written a very simple test application that creates a websocket and parses the data it receives (server sends valid JSON data). The problem is that the first JSON object is parsed successfully, but all the subsequent objects are parsed with errors.

Here's all the code:

$("#connect").click(function ()
    {
        socket = new WebSocket("my server address");
        socket.onopen = function ()
        {
            $("#log").append("Connection opened.<br/>");

            socket.send(/* login information goes here */));
        };
        socket.onerror = function (e)
        {
            $("#log").append("Error: " + e.data + "<br/>");
        };
        socket.onclose = function ()
        {
            $("#log").append("Connection closed.<br/>");
        };
        socket.onmessage = function (e)
        {
            $("#log").append(index.toString() + ": " + e.data + "<br/><br/>");

            console.log("Parsing " + index);
            index++;
            var obj = JSON.parse(e.data);
            console.log("Parsed:");
            console.log(obj);
        };
    });

What I'm getting is: The first time "socket.onmessage" called - JSON is parsed and JS console displays an object. When second one arrives it outputs it to my "log", but JSON.parse fails with error "Uncaught SyntaxError: Unexpected token ILLEGAL". What is puzzling me is that the string that is received is a valid JSON object - I have tested it through several JSON validators. I have even copy-pasted it from my "log" put it in a separate file and parsed it with $.getJSON - and it worked fine, no errors.

Browser: Chrome 13.0.782.112

Any ideas would be helpful.

Thank you.

Upvotes: 4

Views: 19455

Answers (2)

HBP
HBP

Reputation: 16033

ES5 spec http://ecma262-5.com/ELS5_HTML.htm#Section_15.12.1 defines JSON whitespace as tab, cr, lf or sp. The Crockford skip-space uses the following code :

        white = function () {

// Skip whitespace.

            while (ch && ch <= ' ') {
                next();
            }
        },

So if you have any spurious null characters or form-feeds etc in your response then the ES5 JSON parse will throw an error while the Crockford version will not.

Upvotes: 3

Michael
Michael

Reputation: 1076

You should do:

$.parseJSON( json );

see this for more info: http://api.jquery.com/jQuery.parseJSON/

Upvotes: 1

Related Questions