javascript – JSON.parse unexpected token s

javascript – JSON.parse unexpected token s

Youre asking it to parse the JSON text something (not something). Thats 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);

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.

javascript – JSON.parse unexpected token s

Variables (something) are not valid JSON, verify using http://jsonlint.com/

Leave a Reply

Your email address will not be published.