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?
parse() itself cannot execute functions or perform calculations. JSON objects can only hold simple data types and not executable code. If you force code into a JSON object with a string, you must use the Javascript eval() function to convert it into something the Javascript interpreter understands.
Exceptions. Throws a SyntaxError exception if the string to parse is not valid JSON.
The "Unexpected token u in JSON at position 0" error occurs when we pass an undefined value to the JSON. parse or $. parseJSON methods. To solve the error, inspect the value you're trying to parse and make sure it's a valid JSON string before parsing it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With