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?
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?
Share Improve this question asked Oct 31, 2016 at 19:08 AJFaradayAJFaraday 2,4501 gold badge20 silver badges41 bronze badges 5- 5 You're not passing it JSON, which is a problem for a function expecting JSON – adeneo Commented Oct 31, 2016 at 19:09
- @adeneo Possiblyt this doesn't do what I expect. Can you give a valid example? – AJFaraday Commented Oct 31, 2016 at 19:09
- 4 jsonlint. is your friend, as is the spec at json – Quentin Commented Oct 31, 2016 at 19:10
- 9 In JSON, keys and values are quoted with doublequotes, always, unless the values are numbers or other "objects" etc. – adeneo Commented Oct 31, 2016 at 19:10
- Keep in mind that JSON is more strict than javascript notation when creating objects. – S. Buda Commented Oct 31, 2016 at 22:51
1 Answer
Reset to default 15That'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.