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 says:
Uncaught SyntaxError: Unexpected token o
Safari says:
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:
{
"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.
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({});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With