jquery插件没有正确转换JSON字符串

时间:2012-02-16 16:44:39

标签: jquery json comet nan

我通过彗星请求获取JSON字符串。字符串如下:

"{"tab":2,"changedData":{"from":{"line":20,"ch":0},"to":{"line":20,"ch":0},"text":["a"]},"cmd":"copyChunk","timestamp":1329409543902,"person":{"comradeID":"4ef37369b4812","firstName":"","lastName":"","fullName":"ben team2","nickName":"ben t.","messageCount":0,"email":"ben+team2@squadedit.com","lastPing":1329409537308,"sessionLeader":true,"cursorPosition":{"line":0,"ch":0}}}"

我通过jquery json插件运行它:

var r = $.evalJSON(jsonstring);

但它不会正确转换“changeData”对象。其余部分都有效,但changedData.from.line和changedData.to.line都会导致NaN。

我也尝试将changedData.from.line作为字符串发送,然后使用

Number(changedData.from.line)

将其转换回数字,但仍会返回NaN。我几乎肯定20是一个数字,但我以前错了。

提前致谢。

更新

我道歉,开头和结尾的引号实际上并不是字符串的一部分。复制/粘贴的缺陷。

以下是上下文中的代码:

onMessage : function(frame)
{
    //This function calls the handlers.
    //this is fired every time we recieve a message from orbited
    //this is what calls the handler functions
    //body is a json string containing whatever data was sent via the send() function

    delete r;
    //convert the body to an object
    var r = $.evalJSON(frame.body);

其中“frame.body”是上面没有引号的字符串。

2 个答案:

答案 0 :(得分:1)

错误在其他地方。使用parseJSON可以完全使用您提供的字符串http://jsfiddle.net/mendesjuan/qG6Qv/1/

var str = '{"tab":2,"changedData":{"from":{"line":20,"ch":0},"to":{"line":20,"ch":0},"text":["a"]},"cmd":"copyChunk","timestamp":1329409543902,"person":{"comradeID":"4ef37369b4812","firstName":"","lastName":"","fullName":"ben team2","nickName":"ben t.","messageCount":0,"email":"ben+team2@squadedit.com","lastPing":1329409537308,"sessionLeader":true,"cursorPosition":{"line":0,"ch":0}}}';

var json = $.parseJSON(str);
alert(json.changedData.from.line); //outputs 20

可能您的问题是您将parseJSON的返回值分配给变量r,然后您尝试执行Number(changedData.from.line)。没有名为changedData

的变量

答案 1 :(得分:0)

前导和尾随引号"无效。