I keep getting “Uncaught SyntaxError: Unexpected token o”

前端 未结 9 1531
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 01:46

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 t

9条回答
  •  难免孤独
    2020-11-22 02:16

    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.

提交回复
热议问题