0

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

<script>
$.ajax({
   url: "http://swapi.co/api/people/1/"
}).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
});
</script>
mangocaptain
  • 1,435
  • 1
  • 19
  • 31
  • I find it funny that you basically already solved your problem. Notice that the console shows `Object {foo: "bar"}` for `JSON.parse(JSON.stringify({'foo': 'bar'}))`. And `console.log(data)` shows you something similar. Hence `data` is already similar to what `JSON.parse` would return. – Felix Kling Aug 21 '16 at 00:24

1 Answers1

4

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143