JSON.parse意外的字符错误

kri*_*hna 110 javascript json

我收到此错误:

JSON.parse:意外的角色

当我在firebug中运行此语句时:

JSON.parse({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false});
Run Code Online (Sandbox Code Playgroud)

为什么会这样?JSON字符串对我来说似乎是正确的,我也使用JSHint测试它.上述情况下传递的对象是内容类型设置为的服务器响应application/json

ken*_*ytm 222

你没有解析一个字符串,你正在解析一个已经解析过的对象:)

var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
//                    ^                                          ^
//                    if you want to parse, the input should be a string 

var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.
Run Code Online (Sandbox Code Playgroud)

  • 那真好笑.爱它.<3 (5认同)

Scr*_*ode 35

在将对象传递给解析函数之前,只需使用即可确保对该对象进行字符串化 JSON.stringify().

更新了以下行,

JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));

或者如果你有JSON存储在某个变量中:

JSON.parse(JSON.stringify(yourJSONobject));
Run Code Online (Sandbox Code Playgroud)

  • JSON.stringify是老大. (3认同)