14

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

apsillers
  • 112,806
  • 17
  • 235
  • 239
Fred Thomas
  • 217
  • 1
  • 2
  • 6

1 Answers1

32

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
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 2
    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. – PleaseStand Oct 24 '10 at 22:28
  • 1
    @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 Oct 24 '10 at 22:44
  • Or write a function to convert from JavaScript object notation to JSON (e.g. add quotes). That is easy engough to do. – cdiggins Nov 18 '11 at 17:20
  • Somebody understand why this is so ? – commonpike Nov 13 '15 at 20:31