mangocaptain mangocaptain - 2 months ago 8x
Ajax Question

What is a JSON VM747:1 error that happens during JSON parsing?

I'm goofing around with the Star Wars API but don't get why I can't parse the data I get back:

url: ""
}).done(function( data ) {
console.log(JSON.stringify({'foo': 'bar'})) //returns {"foo":"bar"}
console.log(JSON.parse(JSON.stringify({'foo': 'bar'}))) //returns Object {foo: "bar"}
console.log(data); //returns Object {name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair"…}
console.log(JSON.parse(data)) // throws error VM747:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1


data is already an object as you can see by the fact that the console logs Object { ... }, not something like { ... }.

Straight from the chrome console:

enter image description here

Notice the different output for an object and for a string.

So: You don't have to parse anything, just access data directly.

don't get why I can't parse the data

Passing an object to JSON.parse will convert the object to a string. So you end up doing

JSON.parse('[object Object]')

which throws an error because [object Object] is not valid JSON.