If I run this:
eval('{ear: {"<=": 6}}');
I get an error:
Uncaught SyntaxError: Unexpected token :
Let's create the object manually:
var foo = {}; foo.ear = {}; foo.ear["<="] = 6;
Now, the following code:
JSON.stringify(foo)
Returns the following string:
'{"ear":{"<=":6}}'
The same string as the one I started with (except the white characters, but those are irrelevant), so eval(JSON.stringify(foo))
returns the same syntax error error message. However:
$.parseJSON(JSON.stringify(foo))
is executed correctly. What is the reason of that?
EDIT:
As nnnnnn and Ron Dadon pointed out, the initial string and the result of stringify
are different. However, as I pointed out in the question, even the result of stringify
used as input for eval
will result in the syntax error message.
EDIT2:
Based on the answers and experiments conducted, this function is interesting:
function evalJSON(text) { return eval("(" + text + ")"); }
Main {}
are parsed as block statement.
try to wrap in parenthesis:
eval('({ear: {"<=": 6}})');
In javascript {}
can be parsed as a block or an object
examples:
//object var user = { name: "John", age: "32" }; //block { let a = 5; console.log(a); } //object: var a = {}; console.log({}); return {}; ({}); //block: function(){} for(k in o){} {}
Object literal notations need to be evaluated. This happens when you assign a variable:
var a = {ear: {"<=": 6}};
or when you put parentheses around it, a anonymous object:
({ear: {"<=": 6}});
Otherwise curly brackets are parsed as block markers. In your case this means {ear:...}
is a label definition, the label is named ear. The next block {"<=": 6}
gives you a syntax error because "<=": 6
is invalid syntax.
The same applies if you put this into an eval
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With