Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 566
AJFaraday Avatar asked Oct 31 '16 19:10

AJFaraday


People also ask

Why does JSON parse not work?

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.

What error does JSON parse () throw when the string to parse is not valid JSON?

Exceptions. Throws a SyntaxError exception if the string to parse is not valid JSON.

How do I fix unexpected token in JSON error?

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.


1 Answers

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.

like image 53
TimoStaudinger Avatar answered Oct 19 '22 16:10

TimoStaudinger