pass function in json and execute

amateur picture amateur · Oct 16, 2010 · Viewed 63.7k times · Source

Is there any way that I can pass a function as a json string (conversion with JSON.stringify), send it to another function, parse the json and then execute the function that was in the json? I am using jquery and javascript.

Answer

EasierSaidThanDone picture EasierSaidThanDone · Mar 9, 2012

Yes, you can. There are tons of ways to do it.

And there is no need to use the "evil" eval function (please yahoogle why it should be avoided) as pointed out here: http://javascript.about.com/library/bleval.htm

var tmpFunc = new Function(codeToRun);
tmpFunc(); 

Whether it was JSON at any stage should be irrelevant.