Fergoso
Fergoso

Reputation: 1582

Invalid character error when parsing JSON

I'm trying to parse JSON data from an external json file (an Array). But noting is being returned. I'm getting an error (F12) Invalid character. What might be the issue here? How can I fix this?

var myAr;

$.ajax({url: 'test.json'}).done(function(d) {
  myAr = JSON.parse(d); // Invalid character
});

external file:

[ [ "Parrot", "Green"], [ "Swan", "White"] ]

Upvotes: 1

Views: 1028

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

When you retrieve JSON via AJAX using jQuery it will automatically deserialise it for you. Calling JSON.parse() again on the resulting object will cause the error as you've seen. In your code d is already an object containing all the properties returned from the request, ready for you to use:

$.ajax({ url: 'test.json' }).done(function(d) {
    console.log(d); // shows the returned object
});

Upvotes: 3

Related Questions