Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a part of a debugging framework that needs to be able to run time eval objects.

Specifically, if I have a string like this "{a: 1, b:2}" it needs to evaluate it into an object with members a and b with those values. However, if I do eval("{a: 1, b:2}") it seems to evaluate it as a statement, and says something about an illegal label.

I have hacked it so that it evaluates like this:

eval("var x=" + str + "; x;");

which seems to work, but seems like a horrible hack. Any suggestions on how to do this better?

(BTW, I am aware of the dangers of eval, but this is part of a debugging framework that will not be seen by actual users.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
274 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do it using () to have it parse it as an object, rather than a statement, like this:

eval("(" + str + ")");

Though, you should use JSON.parse() first, if the browser supports it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...