Reputation: 2549
I try to change a string into an object using eval but failed.
var obj ="{a:0, b:-1}";
eval(obj);
Error msg says "invalid label" but even this doesn't work
var obj="{'a':'0', 'b':'-1'}";
What's wrong with the code?
Upvotes: 1
Views: 90
Reputation: 2615
you can try something like this too.
var obj=eval(" [{'a':'0', 'b':'-1'}] ");
alert(obj);
Upvotes: 0
Reputation: 51797
when eval
ing json, you have to put braces around it, so it should look like (otherwise it's not a complete javascript-statement):
eval('('+obj+')');
this solved the error, but the generated object isn't saved to any variable - so you might want to end up with something else, like:
eval('obj = '+obj);
this also makes a complete statement and, in addition, obj
now is a "real" object.
Upvotes: 2