开发者

execute a javascript code inside a json object?

is there away?

so something like:

{ key1 : "val1", key2: "va开发者_JAVA百科l2", some_code: "document.getElementById("someid").innerHTML='test';" }

So some_code would be executed without any user intervention?


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.


This would not be JSON anymore. But you can post-process the parsed JSON:

json.some_code = eval(json.some_code);

However this may be dangerous (script injection, etc).

So, if you can, do this instead:

json = { key1 : "val1", key2: "val2", elem: "someid", html:"test" };
document.getElementById(json.elem).innerHTML=json.html;


It is possible to do that, yes, for example by doing this :

{
  "functionName": function() {
    alert('Hello!');
  }()
}

However, that would not be valid JSON anymore. JSON does not accept functions.


Well, first you need to escape the double-quotes:

{ key1 : "val1", key2: "val2", some_code: "document.getElementById(\"someid\").innerHTML='test';" }

(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:

eval(obj.some_code);

This is, of course, very hazardous unless you have absolute control over the contents of some_code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜