6

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.

0

1 Answer 1

14

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({});
Sign up to request clarification or add additional context in comments.

7 Comments

Since when? Agreed I'm using jquery after years, but last I used it, it used to be a string (or was it?)
@CodePoet It's been that way for years.
Ah. I think I see it now, the Response header says Content-Type: application/json, maybe that's why?
You can identify the response type in the client-side call and/or the server-side code. Perhaps you never did thus jQuery didn't have enough information to do the job for you.
@CodePoet: From the docs: "Different types of response to $.ajax() call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option."
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.