Why does the following code needs to add ( and ) for eval?
var strJson = eval("(" + $("#status").val().replace(";","") + ")");
PS: $("#status").val() is returning something like {"10000048":"1","25000175":"2","25000268":"3"};
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
evaltakes a JavaScript statement or expression, but{...}would be valid as a statement or an expression, and the grammar of JavaScript prefers a statement.As an expression:
is an Object with some properties (what you want).
As a statement, it is a block:
which gives an error.
(JavaScript labels can be used to label a particular statement for use with
break/continue. They’re a bit pointless and almost never used.)So by adding the parentheses you resolve the ambiguity. Only an expression can start with
(, so the contents are parsed in an expression context, giving an object literal, not a statement context.Incidentally this is not quite enough to correctly interpret all possible JSON values. Due to an oversight in JSON’s design, the characters U+2028 and U+2029, two obscure Unicode line-ending characters, are valid to put unescaped in a JSON string literal, but not in a JavaScript string literal. If you want to be safe, you can escape them, eg: