Execute javascript code inside json object?

from there?

so something like:

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

So, some_code will be executed without user intervention?

+6
json javascript eval
source share
4 answers

It will no longer be JSON. But you can aftermarket processed JSON:

 json.some_code = eval(json.some_code); 

However, this can 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; 
+3
source share

This can be done, for example, by:

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

However, this is no longer valid JSON. JSON does not accept functions.

+2
source share

Not.

First of all, your example is invalid JSON. Try using the JSON validator .

Secondly, JSON is a data exchange standard and, if properly analyzed, any text that is inside it, which is some code, will not be executed.

Read in JSON Security Concerns .

Rule of thumb: do not use the JavaScript eval function, rather use a ready-made parser such as the Douglas Crockford JSON evaluator .

+2
source share

Well, first you need to avoid double quotes:

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

(Or use single quotes.)

If you want to evaluate some_code field as a script, it is as simple as passing it eval:

 eval(obj.some_code); 

This, of course, is very dangerous if you do not have absolute control over the contents of some_code .

0
source share

All Articles