解析通过WebSocket收到的JSON错误 [英] Parse JSON received with WebSocket results in error

查看:83
本文介绍了解析通过WebSocket收到的JSON错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个非常简单的测试应用程序,该应用程序创建了一个websocket并解析了接收到的数据(服务器发送了有效的JSON数据). 问题在于第一个JSON对象已成功解析,但所有后续对象均被解析为错误.

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.

这是所有代码:

$("#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);
        };
    });

我得到的是:第一次调用"socket.onmessage"-解析JSON,并且JS控制台显示一个对象.当第二个到达时,它将其输出到我的日志"中,但是JSON.parse失败,并显示错误未捕获的SyntaxError:意外的令牌ILLEGAL". 令我感到困惑的是,接收到的字符串是有效的JSON对象-我已经通过多个JSON验证器对其进行了测试.我什至从日志"中将其复制粘贴到一个单独的文件中,并使用$ .getJSON对其进行了解析-并且工作正常,没有错误.

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.

浏览器:Chrome 13.0.782.112

Browser: Chrome 13.0.782.112

任何想法都会有所帮助.

Any ideas would be helpful.

谢谢.

推荐答案

ES5规范 http: //ecma262-5.com/ELS5_HTML.htm#Section_15.12.1 将JSON空格定义为tab,cr,lf或sp. Crockford跳过空间使用以下代码:

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();
            }
        },

因此,如果响应中包含任何虚假的空字符或换页等,则ES5 JSON解析将引发错误,而Crockford版本则不会.

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.

这篇关于解析通过WebSocket收到的JSON错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆