Kyeotic
Kyeotic

Reputation: 19847

Why does JSON.parse("string") fail

According to the JSON spec a string is a legitimate JSON value.

enter image description here

So why does this happen?

Upvotes: 4

Views: 11138

Answers (3)

Alex MDC
Alex MDC

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

Andrew Brown
Andrew Brown

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

Alexander
Alexander

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

Related Questions