javascript eval 和对象评估
我有一个调试框架的一部分,需要能够运行时 eval 对象。
具体来说,如果我有一个像这样的字符串 "{a: 1, b:2}"
它需要将其评估为具有成员 a
和 b 的对象
与这些值。但是,如果我执行 eval("{a: 1, b:2}")
,它似乎会将其评估为一条语句,并说明有关非法标签的内容。
我对它进行了黑客攻击,使其评估如下:
eval("var x=" + str + "; x;");
这似乎有效,但似乎是一个可怕的黑客攻击。关于如何做得更好有什么建议吗?
(顺便说一句,我知道 eval 的危险,但这是调试框架的一部分,实际用户不会看到。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
()
来将其解析为对象,而不是语句,如下所示:不过,您应该首先使用
JSON.parse()
,如果浏览器支持的话。You can do it using
()
to have it parse it as an object, rather than a statement, like this:Though, you should use
JSON.parse()
first, if the browser supports it.