views:

53

answers:

1

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.)

+2  A: 

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.

Nick Craver
JSON.parse() will not work with the examples described because they are not valid JSON. For example, valid JSON encloses all property names in double quotes.
idealmachine
@idealmachine - yes you're correct...at the same time though, I'd argue if you intend to use it as such, why *not* use valid JSON in the first place? In this example, yes the user would need to adjust their object markup.
Nick Craver