Javascript 我不断收到“Uncaught SyntaxError: Unexpected token o”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8081701/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:39:26  来源:igfitidea点击:

I keep getting "Uncaught SyntaxError: Unexpected token o"

javascriptjqueryjson

提问by Bjorninn

I'm trying to learn some html/css/javascript, so I'm writing myself a teaching project.

我正在尝试学习一些 html/css/javascript,所以我正在为自己编写一个教学项目。

The idea was to have some vocabulary contained in a json file which would then be loaded into a table. I managed to load the file in and print out one of its values, after which I began writing the code to load the values into the table.

这个想法是在 json 文件中包含一些词汇,然后将其加载到表中。我设法加载文件并打印出其中一个值,之后我开始编写代码以将值加载到表中。

After doing that I started getting an error, so I removed all the code I had written, leaving me with only one line (the same line that had worked before) ... only the error is still there.

这样做之后,我开始遇到错误,所以我删除了我编写的所有代码,只留下一行(以前工作过的同一行)……只有错误仍然存​​在。

The error is as follows:

错误如下:

Uncaught SyntaxError: Unexpected token o
(anonymous function)script.js:10
jQuery.Callbacks.firejquery-1.7.js:1064
jQuery.Callbacks.self.fireWithjquery-1.7.js:1182
donejquery-1.7.js:7454
jQuery.ajaxTransport.send.callback

My javascript code is contained in a separate file and is simply this:

我的 javascript 代码包含在一个单独的文件中,就是这样:

function loadPageIntoDiv(){
    document.getElementById("wokabWeeks").style.display = "block";
}

function loadWokab(){
    //also tried getJSON which threw the same error
    jQuery.get('wokab.json', function(data) {
        var glacier = JSON.parse(data);
    });
}

And my JSON file just has the following right now:

我的 JSON 文件现在只有以下内容:

[
    {
        "english": "bag",
        "kana": "kaban",
        "kanji": "K"
    },

    {
        "english": "glasses",
        "kana": "megane",
        "kanji": "M"
    }
]

Now the error is reported in line 11 which is the var glacier = JSON.parse(data);line.

现在错误报告在第 11 行,即该var glacier = JSON.parse(data);行。

When I remove the json file I get the error: "GET http://.../wokab.json404 (Not Found)" so I know it's loading it (or at least trying to).

当我删除 json 文件时,我收到错误消息:“GET http://.../wokab.json404 (Not Found)”所以我知道它正在加载它(或至少尝试加载)。

回答by ek_ny

Looks like jQuery takes a guess about the datatype. It does the JSON parsing even though you're not calling getJSON()-- then when you try to call JSON.parse() on an object, you're getting the error.

看起来 jQuery 需要猜测数据类型。即使您没有调用 getJSON(),它也会进行 JSON 解析——然后当您尝试在对象上调用 JSON.parse() 时,您会收到错误消息。

Further explanation can be found in Aditya Mittal's answer.

进一步的解释可以在Aditya Mittal 的回答中找到

回答by Andrius Bentkus

The problem is very simple

问题很简单

jQuery.get('wokab.json', function(data) {
    var glacier = JSON.parse(data);
});

You're parsing it twice. getuses the dataType='json', so data is alreadyin json format. Use $.ajax({ dataType: 'json' ...to specifically set the returned data type!

你解析它两次。get使用dataType='json',所以数据已经是 json 格式。使用$.ajax({ dataType: 'json' ...专门设置返回的数据类型!

回答by Aditya Mittal

Basically if the response header is text/html you need to parse, and if the response header is application/json it is already parsed for you.

基本上如果响应头是 text/html 你需要解析,如果响应头是 application/json 它已经为你解析了。

Parsed data from jquery success handler for text/html response:

来自 jquery 成功处理程序的文本/html 响应的解析数据:

var parsed = JSON.parse(data);

Parsed data from jquery success handler for application/json response:

来自应用程序/json 响应的 jquery 成功处理程序的解析数据:

var parsed = data;

回答by Matthias M

Another hints for Unexpected tokenerrors. There are two major differences between javascript objects and json:

另一个Unexpected token错误提示。javascript 对象和 json 之间有两个主要区别:

  1. json data must be always quoted with double quotes.
  2. keys must be quoted
  1. json 数据必须始终用双引号引用。
  2. 键必须被引用

Correct JSON

正确的 JSON

 {
    "english": "bag",
    "kana": "kaban",
    "kanji": "K"
}

Error JSON 1

错误 JSON 1

 {
    'english': 'bag',
    'kana': 'kaban',
    'kanji': 'K'
 }

Error JSON 2

错误 JSON 2

 {
    english: "bag",
    kana: "kaban",
    kanji: "K"
}

Remark

评论

This is not a direct answer for that question. But it's an answer for Unexpected tokenerrors. So it may be help others who stumple upon that question.

这不是该问题的直接答案。但这是Unexpected token错误的答案。因此,它可能会帮助其他遇到该问题的人。

回答by Muhammad Soliman

Simply the response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o" however you have to specify datatype in your request to be of type dataType='json'

简单的响应已经被解析,你不需要再次解析它。如果您再次解析它,它将为您提供“意外令牌 o”,但是您必须在请求中指定数据类型为类型dataType='json'

回答by Brandon

I had a similar problem just now and my solution might help. I'm using an iframe to upload and convert an xml file to json and send it back behind the scenes, and Chrome was adding some garbage to the incoming data that only would show up intermittently and cause the "Uncaught SyntaxError: Unexpected token o" error.

我刚才遇到了类似的问题,我的解决方案可能会有所帮助。我正在使用 iframe 上传一个 xml 文件并将其转换为 json 并在后台将其发送回,Chrome 正在向传入数据中添加一些垃圾,这些垃圾只会间歇性地显示并导致“未捕获的语法错误:意外的令牌 o”错误。

I was accessing the iframe data like this:

我正在像这样访问 iframe 数据:

$('#load-file-iframe').contents().text()

which worked fine on localhost, but when I uploaded it to the server it stopped working only with some files and only when loading the files in a certain order. I don't really know what caused it, but this fixed it. I changed the line above to

它在本地主机上运行良好,但是当我将它上传到服务器时,它仅停止处理某些文件,并且仅在按特定顺序加载文件时停止工作。我真的不知道是什么原因造成的,但这修复了它。我将上面的行更改为

$('#load-file-iframe').contents().find('body').text()

once I noticed some garbage in the HTML response.

一旦我注意到 HTML 响应中有一些垃圾。

Long story short check your raw HTML response data and you might turn something up.

长话短说检查您的原始 HTML 响应数据,您可能会发现一些问题。

回答by Obinwanne Hill

SyntaxError: Unexpected token o in JSON

This also happens when you forget to use the awaitkeyword for a method that returns JSON data.

当您忘记为await返回 JSON 数据的方法使用关键字时,也会发生这种情况。

For example:

例如:

async function returnJSONData()
{
   return "{\"prop\": 2}";
}

var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);

will throw an error because of the missing await. What is actually returned is a Promise[object], not a string.

会因为缺少await. 实际返回的是Promise[object],而不是string.

To fix just add await as you're supposed to:

要修复,只需按预期添加等待:

var json_str = await returnJSONData();

This should be pretty obvious, but the error is called on JSON.parse, so it's easy to miss if there's some distancebetween your awaitmethod call and the JSON.parsecall.

这应该很明显,但是错误是在 上调用的JSON.parse,因此如果您的方法调用和调用之间存在一定距离,则很容易错过。awaitJSON.parse

回答by VISHAL KUMAR

const getCircularReplacer = () => {
              const seen = new WeakSet();
              return (key, value) => {
                if (typeof value === "object" && value !== null) {
                  if (seen.has(value)) {
                    return;
                  }
                  seen.add(value);
                }
                return value;
              };
            };
JSON.stringify(tempActivity, getCircularReplacer());

Where tempActivity is fething the data which produces the error "SyntaxError: Unexpected token o in JSON at position 1 - Stack Overflow"

tempActivity 正在处理产生错误“SyntaxError:Unexpected token o in JSON at position 1 - VoidCC”的数据

回答by thexebolud

Make sure your JSON file does not have any trailing characters before or after. Maybe an unprintable one? You may want to try this way:

确保您的 JSON 文件前后没有任何尾随字符。也许是无法打印的?您可能想尝试这种方式:

[{"english":"bag","kana":"kaban","kanji":"K"},{"english":"glasses","kana":"megane","kanji":"M"}]