看似有效的JSON上的JSON.parse错误 [英] JSON.parse error on a seemingly valid JSON

查看:131
本文介绍了看似有效的JSON上的JSON.parse错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JSON.parse()来解析从api返回的 json (Laravel 5)使用jquery的 $。get()调用。 json 看似有效,但 JSON.parse()在Safari和Chrome中都返回错误。

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

Chrome说:

Uncaught SyntaxError: Unexpected token o

Safari说:

SyntaxError: JSON Parse error: Unexpected identifier "object"

代码片段如下所示:

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

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"
}

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

Interestingly, eval() works just fine.

推荐答案

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

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

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

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

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

JSON.parse({});

这篇关于看似有效的JSON上的JSON.parse错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆