I am trying to use JSON.parse
to parse a string to the array of array, such as
var a = "[['1909-23', 'egg']]"
JSON.parse(a)
It gives me the SytaxError. Wonder if there is any easy way to solve it. Thanks.
I am trying to use JSON.parse
to parse a string to the array of array, such as
var a = "[['1909-23', 'egg']]"
JSON.parse(a)
It gives me the SytaxError. Wonder if there is any easy way to solve it. Thanks.
The string
"[['1909-23', 'egg']]"
Is not a valid JSON string. As such you can't call JSON.parse()
on it.
The JSON format requires double quotes around strings.
A solution would be then to use double quotes:
var a = '[["1909-23", "egg"]]';
console.log(JSON.parse(a));
Before you use this, please read Why is using the JavaScript eval function a bad idea?. This will potentially open up your JavaScript to code injection attacks. A much better solution is to actually turn your string into correct JSON and parse is using JSON.parse
That all said, you can “parse” (actually you've executing the string as javascript, hence the injection problem) this string using eval
.
var a = "[['1909-23', 'egg']]"
var b = eval(a);
console.log(b);
Note the warning on MDN
Do not ever use eval!
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.
eval() is also slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.
Additionally, modern javascript interpreters convert javascript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of eval will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set it's value. Additonally, new things can be introduced to that variable through eval() such as changing the type of that variable, forcing the browser to reevaluate all of the generated machine code to compensate. However, there (thankfully) exists a very good alternative to eval: simply using window.Function. As an example of how you convert code using evil eval() to using Function(),