0

In my angularjs app I'm getting this JSON from an API:

[
  {
    'Foo': 'bar'
   }
]

Unfortunately - SyntaxError: Unexpected token ' at Object.parse (native)

Is there any way to fix this client-side without changing the API?

Artur Stary
  • 724
  • 2
  • 13
  • 30

1 Answers1

4

That's not JSON. It's something JSON-like, but JSON requires that strings and property keys be in double, not single, quotes.

So the answer is: Correct the API. If you don't control it, tell the people controlling it that it's wrong.

If you absolutely need to support that broken response, you might look at modifying one of Crockford's JSON parsers to make it support single-quoted keys and strings, which shouldn't be very hard at all. Or you might use PEG.js to generate your own parser (possibly starting with their JavaScript parser), but that would be more work.

You'll get people telling you you can parse that with eval, and it's true, you can:

// LAST RESORT
var data = eval("(" + response + ")");

...but note that eval will run any arbitrary code in the response, it doesn't just parse data structures. So you'd have to absolutely trust the API not to send back something malicious, something that tracks your users, etc.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875