Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSON.parse("string") fail

Tags:

json

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

enter image description here

So why does this happen?

like image 639
Kyeotic Avatar asked Dec 15 '22 07:12

Kyeotic


2 Answers

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.

like image 181
Alex MDC Avatar answered Jan 05 '23 13:01

Alex MDC


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.

like image 25
Alexander Avatar answered Jan 05 '23 12:01

Alexander