JSON 中的 Javascript Unexpected Token B

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

JSON in Javascript Unexpected Token B

javascriptjson

提问by cjds

I'm parsing the following string in JSON

我正在解析 JSON 中的以下字符串

http://jsfiddle.net/cjds/9mJbq/2/

http://jsfiddle.net/cjds/9mJbq/2/

When I run it chrome throws up the following error Unexpected Token B.

当我运行它时,chrome 会引发以下错误Unexpected Token B

Can't figure it out. Because the string is created by PHP json_encode so there shouldn't be a problem with the JSON.

想不通 因为字符串是由 PHP json_encode 创建的,所以 JSON 应该没有问题。

I ran it through JSONLint and there was no error so the JSON is fine.

我通过 JSONLint 运行它并且没有错误,所以 JSON 很好。

So what's the error?

那么错误是什么?

回答by Brian Park

The parameter for JSON.parse() should be string.

JSON.parse() 的参数应该是字符串。

Thus, JSON.parse(["hello", "world"])is wrong.

因此,JSON.parse(["hello", "world"])是错误的。

It should be JSON.parse("[\"hello\", \"world\"]")

它应该是 JSON.parse("[\"hello\", \"world\"]")

I updated the jsfiddle. Take a look at http://jsfiddle.net/9mJbq/3/

我更新了 jsfiddle。看看http://jsfiddle.net/9mJbq/3/

回答by JoeTidee

For others arriving at this question, this error occurs if your ajax request is returning 'Bad Request' (error 400) and the json parser is expecting json. For example:

对于遇到此问题的其他人,如果您的 ajax 请求返回“错误请求”(错误 400)并且 json 解析器正在等待 json,则会发生此错误。例如:

const fetchSomething = url =>
    fetch(url).then(data => data.json());