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.

7 Answers 7

62

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.

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

7 Comments

+1 for "yahoogle". Though isn't Bing more popular than Yahoo these days? Would that be "bingle"? Or the longer phrase Scott Hanselman has used in presentations "Google it on Bing"?
I agree @GregL, but I coined this phrase some time ago and just don't want to let it go! Using "bingle", "bingoogle"... just doesn't sound right to me. Plus there are plenty of words and proverbs in the English language that refer to outdated things...
not bad @webnoob but it's too late to change now, 'yahoogle' has gone viral
I shall make it happen! :)
what of yahingle and ginglehoo
|
22

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();

1 Comment

Why the extra set of ( ) inside eval ?
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();
});​

Comments

5

take a look at the JSONfn plugin.

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

it does exactly what you're asking for.

-Vadim

Comments

3

I created a fork of JSONfn which enables you to stringify and parse objects and their prototypes. In my basic tests it worked fine.

https://github.com/cgarciae/jsonfn

Comments

1

I've found it helpful to use the JavaScript call() function when working with functions in JSON files.

var returnData = theJsonData.theFunction.call();
console.log(returnData); // prints any return data

I hope that helps anyone that stops by!

Comments

-11

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.

4 Comments

JSON = JavaScript Object Notation - of course the function can be serialized and passed to and fro. What is an object ? Pretty much anything in JS, functions included. Get a bit annoyed when someone says "No" when "YES" is the proper answer. Better to say 'not that I am aware of'. Bill
I'd think ten times before saying that smt is not possible in JavaScript :) Hardly can recall even a few "NO"s in JS per se. "HOW" and "WHY NOT" are the most common questions.
@ArmanMcHitarian You forgot the third-most-common question: "WHY IN THE WORLD DOES IT DO THAT!?"
As others have pointed out this can be done.

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.