ChatGPT解决这个技术问题 Extra ChatGPT

I keep getting "Uncaught SyntaxError: Unexpected token o"

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

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.

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:

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:

[
    {
        "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.

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

$.get can recognize json when it sent, hence. var glacier = data; should suffice.
Summing up: you're trying to parse it twice.
I got the similar Uncaught SyntaxError: Unexpected token I because Python encodes json.dumps([float('inf'),float('nan')]) == '[Infinity, NaN]'

C
Community

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.

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


Aha, so data[0].english returns "bag". Looks like I don't have to parse the json file at all.
that's interesting.. I guess jquery takes a guess at datatype and assumes it's json. I would think that getJson would work then as well, right?
Small note: if you JSON.parse an object the "Unexpected token o" is thrown simply because it tries to parse obj_to_parse.toString(), which is [object Object]. Try to JSON.parse('[object Object]'); ;)
It happened to me too, I think my error was that I tried to parse to JSON something that already was a JSON Object
jQuery doesn't guess. If you don't override it with dataType (any why would you), it uses the Content-type HTTP header of the response to determine what sort of data it is, and parses it if it is one that jQuery recognises.
P
ProblemsOfSumit

The problem is very simple

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

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


A
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.

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

var parsed = JSON.parse(data);

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

var parsed = data;

Note to anyone voting this down, the accepted answer above contains exact copy from this answer. Adding link from accepted answer now.
M
Matthias M

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

json data must be always quoted with double quotes. keys must be quoted

Correct JSON

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

Error JSON 1

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

Error 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 token errors. So it may be help others who stumple upon that question.


M
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'


B
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.

I was accessing the iframe data like this:

$('#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.

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


OK, thanks. Strangely it sometimes seems to receive an already parsed json object and sometimes not. I haven't had time to continue the project so I don't know if it will randomly do this (depending on browsers and systems or something). Thanks for the pointer I'll keep it in mind.
O
ObiHill
SyntaxError: Unexpected token o in JSON

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

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.

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 distance between your await method call and the JSON.parse call.


t
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:

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

JSON.parse('[{"english":"bag","kana":"kaban","kanji":"K"},{"english":"glasses","kana":"megane","kanji":"M"}]'); Works fine. ¿Have you try replacing that line with alert(data) to check if the file is loading correctly?
V
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"