NSF
NSF

Reputation: 2549

eval refused to change string into object in Javascript

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

Answers (2)

Sunil Dodiya
Sunil Dodiya

Reputation: 2615

you can try something like this too.

var obj=eval(" [{'a':'0', 'b':'-1'}] ");
alert(obj);

Upvotes: 0

oezi
oezi

Reputation: 51797

when evaling 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

Related Questions