简体   繁体   English

为什么此JSON.parse返回错误:“意外的令牌非法”?

[英]Why does this JSON.parse return error: “unexpected token illegal”?

I'm using an AJAX request. 我正在使用AJAX请求。 This is the first time I'm using JSON or any of it's methods. 这是我第一次使用JSON或其任何方法。 The ajax utility returns an argument to the onreadystatechange callback as the responseText or responseXML of the file I'm requesting. ajax实用程序将一个参数作为我请求文件的responseText或responseXML返回到onreadystatechange回调。 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. 使用简单的info.txtrequest.responseText可以很好地工作,但是当我尝试info.jsJSON.parse时,如果我多次检查语法是否正确,它将返回“意外的令牌非法”。 Here is the JSON: 这是JSON:

JSON: JSON:

{
    first: 1,
    second: 2
}

JSON.parse() is very strict in grammar. JSON.parse()在语法上非常严格。 The key/value pairs should have the form: 键/值对应采用以下形式:

string:value

So the "first" and "second" should be string in a JSON object. 因此,“第一个”和“第二个”应该是JSON对象中的字符串。 Change your JSON to following code and it should be right 将您的JSON更改为以下代码,它应该是正确的

{
    "first": 1,
    "second": 2
}

You seem to already be using jQuery in your success callback. 您似乎已经在成功回调中使用了jQuery。 jQuery also has methods to perform AJAX requests such as $.ajax rendering your AJAX custom function pretty useless. jQuery还具有执行AJAX请求的方法,例如$.ajax使您的AJAX自定义函数非常无用。 In your case you seem to be requesting a javascript file (.js) which is different than JSON. 就您而言,您似乎在请求一个不同于JSON的JavaScript文件(.js)。 So: 所以:

(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. 话虽如此,您仍然可以继续使用您的方法,但是如果您的json.js不包含有效的JSON字符串, JSON.parse(e)将始终失败。 To verify that it contains a valid JSON string you could validate it on http://jsonlint.com 要验证其是否包含有效的JSON字符串,您可以在http://jsonlint.com上对其进行验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM