Alex Rivera | Logout

pass function in json and execute

Asked 2010-10-15T23:57:21.867
39

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.

Edit
Report

2 Answers

20

Here's a working example

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();
});​
answered 2010-10-16T00:16:00.427
5

take a look at the JSONfn plugin.

http://www.eslinstructor.net/jsonfn/

it does exactly what you're asking for.

-Vadim

answered 2012-09-07T06:57:43.987

Your Answer