Reputation: 19847
According to the JSON spec a string is a legitimate JSON value.
So why does this happen?
Upvotes: 4
Views: 11138
Reputation: 2456
You are actually passing the bare word string
in to the the function which of course is not valid JSON. To actually pass in the value "string
" you need to be careful with your JavaScript.
Try this:
JSON.parse("\"string\"")
The extra pair of quotes must be escaped so they become part of the value you pass in to the function.
Upvotes: 15
Reputation: 4126
Because a string in JSON must be surrounded by quotation marks, and in your JSON.parse("string")
call, JSON.parse
never "sees" any quotation marks as part of the text it is asked to parse. The double-quotes that we see are being used to form a legal string to pass in -- they're not part of the text we're passing in.
This call works:
JSON.parse('"s"')
Upvotes: 0
Reputation: 2052
The Syntax error tells you: "s" is an unexpected token. A string is a valid JSON value but as the spec describes it must be enclosed in double quotes.
string
""
" chars "
Generally, you can use JSON.stringify(myValue)
to check what a properly formatted JSON string of such value would be.
Upvotes: 1