views:

52

answers:

4

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.

A: 

No, you cannot do this. Functions cannot be JSON serialized. Instead of converting the object into JSON you could directly pass it to the other function without calling JSON.stringify.

Darin Dimitrov
I have a feeling he's traversing a wire somewheres ...
drachenstern
A: 

Yes. Simply use javascript's eval function:

var functionName;
var result = eval(functionName + "()");
tster
+2  A: 

Yes, you can convert a function to a string with it's toString() method.

Here's an example to show converting a function to a string and back to a function:

var myfunc = function () {
    alert('It works!');
}

var as_string = myfunc.toString();

as_string = as_string.replace('It works', 'It really works');

var as_func = eval('(' + as_string + ')');

as_func();
Skilldrick
+1  A: 

Here's a working example: http://jsfiddle.net/gfbAg/

Basically, you have to be careful with this sort of thing. If you take an extant javascript function, turn it to a string, and eval it, you might run into function redeclaration issues. If you are simply taking a function string from the server and you want to run it, you can do as I did on that jsfiddle:

Javascript

var myFunc = "function test() {alert('test');}";

$(document).ready(function() {
    var data = new Object();
    data.func = myFunc;
    var jsonVal = $.toJSON(data);
    var newObj = $.evalJSON(jsonVal);
    eval(newObj.func);
    test();
});​
treeface
cool - thanks for this
Niall Collins