1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That's interesting...Actually I didn't use brackets previously but instead put string into a literal array so it's something like: obj = eval("[string]"); and it worked. So I didn't notice that issue. Thanks. I'll try it now.
why do the obj = inside the eval? eval returns the result; simply assign that: obj = eval('('+obj+')'); Do as little with eval as possible
0

you can try something like this too.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.