javascript eval 和对象评估

发布于 2024-09-29 01:13:11 字数 395 浏览 1 评论 0原文

我有一个调试框架的一部分,需要能够运行时 eval 对象。

具体来说,如果我有一个像这样的字符串 "{a: 1, b:2}" 它需要将其评估为具有成员 ab 的对象 与这些值。但是,如果我执行 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月打碎记忆 2024-10-06 01:13:11

您可以使用 () 来将其解析为对象,而不是语句,如下所示:

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

不过,您应该首先使用 JSON.parse() ,如果浏览器支持的话。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文