Javascript JSON.parse 意外字符错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8524933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.parse unexpected character error
提问by krishna
I get this error:
我收到此错误:
JSON.parse: unexpected character
JSON.parse:意外字符
when I run this statement in firebug:
当我在 firebug 中运行此语句时:
JSON.parse({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false});
Why is it so? The JSON string seems correct to me and I also tested it using JSHint. The passed object in the above case is a server response with content type set to application/json
为什么会这样?JSON 字符串对我来说似乎是正确的,我还使用 JSHint 对其进行了测试。上述案例中传递的对象是内容类型设置为的服务器响应application/json
回答by kennytm
You're not parsing a string, you're parsing an already-parsed object :)
您不是在解析字符串,而是在解析已解析的对象:)
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.
回答by ScrapCode
You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify()
.
您可以通过简单地使用 JSON.stringify()
.
Updated your line below,
在下面更新了您的行,
JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));
JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));
or if you have JSON stored in some variable:
或者如果您将 JSON 存储在某个变量中:
JSON.parse(JSON.stringify(yourJSONobject));
回答by atomh33ls
Not true for the OP, but this error can be caused by using single quotation marks ('
) instead of double ("
) for strings.
对于 OP 而言并非如此,但此错误可能是由对字符串使用单引号 ( '
) 而不是双引号 ( )引起的"
。
The JSON specrequires double quotation marks for strings.
的JSON规范需要字符串双引号。
E.g:
例如:
JSON.parse(`{"myparam": 'myString'}`)
gives the error, whereas
给出错误,而
JSON.parse(`{"myparam": "myString"}`)
does not. Note the quotation marks around myString
.
才不是。注意周围的引号myString
。