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?
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?
Share Improve this question edited Jan 31, 2011 at 10:39 Sebastian Paaske Tørholm 50.9k11 gold badges102 silver badges121 bronze badges asked Jan 31, 2011 at 10:38 David AngDavid Ang 1871 gold badge1 silver badge6 bronze badges 1- As below, yes you could. However, it's best avoided. If you're providing this to a 3rd party is should get blocked. – Iain Ballard Commented Jan 31, 2011 at 10:44
4 Answers
Reset to default 4No.
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;
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
.
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.