Javascript 看似有效的 JSON 上的 JSON.parse 错误

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

JSON.parse error on a seemingly valid JSON

javascriptjqueryjsonlaravel-5

提问by Code Poet

I'm using JSON.parse()to parse a jsonthat's being returned from an api (Laravel 5) called using jquery's $.get(). The jsonis seemingly valid, however, JSON.parse()is returning error in both Safari and Chrome.

我正在使用JSON.parse()解析json从使用 jquery 调用的 api(Laravel 5)返回的$.get(). 在json似乎是有效的,但是,JSON.parse()在Safari和Chrome浏览器返回错误。

Chrome says:

铬 说:

Uncaught SyntaxError: Unexpected token o

Safari says:

Safari 说:

SyntaxError: JSON Parse error: Unexpected identifier "object"

The code fragment is as below:

代码片段如下:

    $.get('/foo/' + product_id, function(data){
        console.log(data);
        var product = JSON.parse(data);
        if (product) {
            // do something
        }
     });

The JSON is:

JSON 是:

{  
   "id":"1b7b3eb7-8769-48fe-a421-64c105de3eff",
   "parent":null,
   "org_id":"845d0d53-de68-42c3-9007-c3d0e72c555e",
   "category_id":"e58237f7-e040-4098-8d46-b84f8cdf7d83",
   "purchase_tax":null,
   "sale_tax":null,
   "code":"982",
   "name":"Mr. Destin Hoppe",
   "is_purchased":false,
   "is_sold":false,
   "purchase_price":null,
   "selling_price":null,
   "purchase_includes_tax":false,
   "sale_includes_tax":false,
   "created_at":"2015-09-16 17:39:34",
   "updated_at":"2015-09-16 17:39:34"
}

Interestingly, eval()works just fine.

有趣的是,eval()工作得很好。

回答by Drew Gaynor

The error is a result of databeing an object, not JSON. You don't need to parse anything; it is already a JavaScript object. jQuery does the parsing within its getmethod. To confirm this, add this line to the top of the callback.

该错误是data对象的结果,而不是 JSON。你不需要解析任何东西;它已经是一个 JavaScript 对象。jQuery 在其get方法中进行解析。要确认这一点,请将此行添加到回调的顶部。

console.log(data["id"]);

As another example of this error, the following line will also fail for the same reason.

作为此错误的另一个示例,以下行也将因相同原因而失败。

JSON.parse({});