Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse unexpected token s

Why is it that whenever I do :-

JSON.parse('"something"') 

it just parses fine but when I do:-

var m = "something"; JSON.parse(m); 

it gives me an error saying:-

Unexpected token s 
like image 894
shriek Avatar asked Sep 13 '13 17:09

shriek


People also ask

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.

How do you handle JSON parsing error?

The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.

What is JSON parse?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

What does this mean SyntaxError unexpected token in JSON at position 0?

Re: Unexpected token in JSON at position 0 This usually means that an error has been returned and that's not valid JSON. Check the browser developer tools console and network tabs.


2 Answers

You're asking it to parse the JSON text something (not "something"). That's invalid JSON, strings must be in double quotes.

If you want an equivalent to your first example:

var s = '"something"'; var result = JSON.parse(s); 
like image 191
T.J. Crowder Avatar answered Sep 24 '22 19:09

T.J. Crowder


What you are passing to JSON.parse method must be a valid JSON after removing the wrapping quotes for string.

so something is not a valid JSON but "something" is.

A valid JSON is -

JSON = null     /* boolean literal */     or true or false     /* A JavaScript Number Leading zeroes are prohibited; a decimal point must be followed by at least one digit.*/     or JSONNumber     /* Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted.*/     or JSONString      /* Property names must be double-quoted strings; trailing commas are forbidden. */     or JSONObject     or JSONArray 

Examples -

JSON.parse('{}'); // {} JSON.parse('true'); // true JSON.parse('"foo"'); // "foo" JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] JSON.parse('null'); // null  JSON.parse("'foo'"); // error since string should be wrapped by double quotes 

You may want to look JSON.

like image 37
Moazzam Khan Avatar answered Sep 21 '22 19:09

Moazzam Khan