在 json 对象中执行 javascript 代码?
有远吗?
所以类似:
{ key1 : "val1", key2: "val2", some_code: "document.getElementById("someid").innerHTML='test';" }
那么 some_code 将在没有任何用户干预的情况下执行?
is there away?
so something like:
{ key1 : "val1", key2: "val2", some_code: "document.getElementById("someid").innerHTML='test';" }
So some_code would be executed without any user intervention?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不。
首先,您的示例不是有效的 JSON。在 JSON 验证器 上尝试一下。
其次,JSON 是一种数据交换标准,当正确解析时,其中包含某些代码的任何文本都不会被执行。
阅读 JSON 安全问题。
经验法则:不要使用 JavaScript
eval
函数,而是使用现成的解析器,例如 Douglas Crockford 的 JSON 评估器。No.
First of all, your example isn't valid JSON. Try it out at JSON validator.
Second of all, JSON is a data exchange standard and when properly parsed, any text that inside of it that is some code will not be executed.
Read on JSON security issues.
Rule of thumb: don't use JavaScript
eval
function, rather use a ready made parser such as Douglas Crockford's JSON evaluator.这不再是 JSON。但是您可以对解析后的 JSON 进行后处理:
但这可能很危险(脚本注入等)。
所以,如果可以的话,请这样做:
This would not be JSON anymore. But you can post-process the parsed JSON:
However this may be dangerous (script injection, etc).
So, if you can, do this instead:
好吧,首先您需要转义双引号:(
或使用单引号。)
如果您想将
some_code
字段作为脚本进行计算,只需将其传递给 eval 即可:这是当然,除非你对
some_code
的内容有绝对的控制权,否则这是非常危险的。Well, first you need to escape the double-quotes:
(Or use single-quotes.)
If you want to evaluate the
some_code
field as a script, it's as simple as passing it to eval:This is, of course, very hazardous unless you have absolute control over the contents of
some_code
.是的,可以这样做,例如这样做:
但是,这不再是有效的 JSON。 JSON 不接受函数。
It is possible to do that, yes, for example by doing this :
However, that would not be valid JSON anymore. JSON does not accept functions.