execute a javascript code inside a json object?

18,699

Solution 1

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.

Solution 2

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;

Solution 3

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.

Solution 4

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.

Share:
18,699
David Ang
Author by

David Ang

Updated on June 23, 2022

Comments

  • David Ang
    David Ang almost 2 years

    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?

  • David Ang
    David Ang over 13 years
    hmm - a little difficult to construct and pass that structure from a backend server to the client browser eh?
  • David Ang
    David Ang over 13 years
    okay thanks guys - i think id probaly stick to that - json as data and no possible way to "self execute" a json object.