AJFaraday AJFaraday - 7 months ago 36
JSON Question

JSON.parse, what am I doing wrong?

So, I'm trying to parse some JSON in Javascript. This feels like it should work, but I'm getting an error. Here's the function call:

JSON.parse("{player: 'green', direction: 'north'}");

And here's the error

VM156:1 Uncaught SyntaxError: Unexpected token p in JSON at position 1
at Object.parse (native)
at <anonymous>:1:6

I'm trying this on an empty web page, no JS libraries are present.

The string, just executed as Javascript creates an object with the two expected attributes.

I've tried wrapping the keys in strings. That didn't parse.

The unexpected token appears to be whatever the first letter is.

What am I doing wrong, how can I parse this object?


That's not valid JSON.

Try this:

JSON.parse('{"player": "green", "direction": "north"}');

Note the double quotes " instead of single quotes ' and the quotes around the object keys.