javascript 为什么这个 JSON.parse 返回错误:“意外令牌非法”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7299644/
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
Why does this JSON.parse return error: "unexpected token illegal"?
提问by 0x499602D2
I'm using an AJAX request. This is the first time I'm using JSON or any of it's methods. The ajax utility returns an argument to the onreadystatechange callback as the responseText or responseXML of the file I'm requesting. Using a simple info.txt
and request.responseText
will work fine but when I try info.js
and JSON.parse
it returns "Unexpected token ILLEGAL" when I've checked multiple times that my syntax is correct. Here is the JSON:
我正在使用 AJAX 请求。这是我第一次使用 JSON 或其任何方法。ajax 实用程序将一个参数作为我请求的文件的 responseText 或 responseXML 返回给 onreadystatechange 回调。使用简单的info.txt
并且request.responseText
可以正常工作,但是当我尝试多次检查我的语法是否正确时info.js
,JSON.parse
它返回“意外的令牌非法”。这是JSON:
JSON:
JSON:
{
first: 1,
second: 2
}
回答by Guan Yuxin
JSON.parse()
is very strict in grammar. The key/value pairs should have the form:
JSON.parse()
语法非常严格。键/值对应具有以下形式:
string:value
So the "first" and "second" should be string in a JSON object. Change your JSON to following code and it should be right
所以“第一个”和“第二个”应该是 JSON 对象中的字符串。将您的 JSON 更改为以下代码,它应该是正确的
{
"first": 1,
"second": 2
}
回答by Darin Dimitrov
You seem to already be using jQuery in your success callback. jQuery also has methods to perform AJAX requests such as $.ajax
rendering your AJAX custom function pretty useless. In your case you seem to be requesting a javascript file (.js) which is different than JSON. So:
您似乎已经在成功回调中使用了 jQuery。jQuery 还具有执行 AJAX 请求的方法,例如$.ajax
使您的 AJAX 自定义函数变得毫无用处。在您的情况下,您似乎正在请求一个与 JSON 不同的 javascript 文件 (.js)。所以:
(function() {
$.getScript('json.js', function(result) {
// TODO: do something with the result
});
})();
or if it is JSON:
或者如果是 JSON:
(function() {
$.getJSON('json.js', function(result) {
// TODO: do something with the result
});
})();
This being said you could still continue to use your method but JSON.parse(e)
will always fail if your json.js
doesn't contain a valid JSON string. To verify that it contains a valid JSON string you could validate it on http://jsonlint.com
话虽如此,您仍然可以继续使用您的方法,但JSON.parse(e)
如果您的方法json.js
不包含有效的 JSON 字符串,则总是会失败。要验证它是否包含有效的 JSON 字符串,您可以在http://jsonlint.com上验证它