9

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?

1
  • As below, yes you could. However, it's best avoided. If you're providing this to a 3rd party is should get blocked. Commented Jan 31, 2011 at 10:44

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

okay thanks guys - i think id probaly stick to that - json as data and no possible way to "self execute" a json object.
3

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;

Comments

2

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.

Comments

1

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.

1 Comment

hmm - a little difficult to construct and pass that structure from a backend server to the client browser eh?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.