Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a JSON string to a function in javascript?

How can I convert a string in javascript/jquery to a function?

I am trying to use a JSON parameter list to initialize a function. However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.

For example, if my JSON is:

json = { "one": 700, "two": "function(e){alert(e);}" }

Then in my code:

parameters = eval(json);
$('myDiv').addThisFeature({
 parameter_1: json.one,
 parameter_2: eval(json.two)  // <= generates error
})
like image 882
Adam Morris Avatar asked Dec 14 '10 18:12

Adam Morris


2 Answers

Example: http://jsfiddle.net/patrick_dw/vs83H/

var json = '{ "one": 700, "two": "function(e){alert(e);}" }';
var parameters = JSON.parse( json );
eval( 'var func = ' + parameters.two );
func( 'test' ); // alerts "test"

You'll need to load the JSON library in browsers that don't support it.

Or do two separate evals:

Example: http://jsfiddle.net/patrick_dw/vs83H/1/

var json = '{ "one": 700, "two": "function(e){alert(e);}" }';
eval( 'var parameters = ' + json );
eval( 'var func = ' + parameters.two );
func( 'test' );

I assume you're aware of the dangers of eval.

like image 74
user113716 Avatar answered Sep 20 '22 21:09

user113716


Looking for a way to not use eval this is the best I could come up with. Use the Function constructor to create a function from a string.

var parsed = JSON.parse('{"one":"700", "two":"function(){return 0;}" }');
var func = new Function('return ' + parsed.two)(); // return parsed.two function
alert(typeof func); // function
alert(func()) // 0
like image 28
Josiah Ruddell Avatar answered Sep 23 '22 21:09

Josiah Ruddell