9

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
})
1
  • Thanks - I do know JSON is data-only... I'm trying to initialize jqGrid object with a changing parameter list, and I occasionally use one parameter takes a function... and in this case, as the function itself has changing internal data, it's easier to generate it and send it across as a string, then define it in my library and initialize it separately. Commented Dec 14, 2010 at 18:53

6 Answers 6

7

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.

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

3 Comments

Thanks - works great. I get the json back from jquery's $().getJSON(), which parses it without eval.
Thanks - that works great. I've heard often that eval is evil - but I don't really know why. JSON.parse() and jquery's $.parseJson() don't seem to evaluate the function - so it looks like I need to use eval(). However, if someone wanted to abuse this, they'd have to know the specific parameter, as jquery returns a parsed object from a $.getJSON() call.
@Adam: If you know that you have absolute control over the content being evaled, you're fine. It's just that it executes any string representation of javascript you give it, so if there's any possibility that someone could pass some malicious code, then it shouldn't be used.
1

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

2 Comments

I think you want to remove the comment :)
JSON object doesnt exist in all browsers. IE7 or earlier do not have it
1

Use this:

parameters = eval('(' + json + ')');
$('#myDiv').addThisFeature({
 parameter_1: parameters.one,
 parameter_2: eval('(' + parameters.two + ')')  // <= does not generate an error
});

Adding the parentheses at the beginning and end of the string prevents the syntax error.

Note, however, that you are parsing JSON using eval (which in some cases has security risks, but I assume that is irrelevant because you do want to run arbitrary code sent by the server). If you have the server-side flexibility (to send invalid JSON), you could just send the function not quoted as a string and eval should be able to parse that just fine.

1 Comment

Thank you - just saw this... it's much cleaner than defining a separate variable for the function.
0

See this SO question. As was said, JSON is meant to hold data. To treat a piece of the data as a function, you would first need to eval the string.

Comments

0

You are eval'ing an anonymous function, which of course won't be called by anything. If you really wanted to run the code in the json then the text would need to be alert(e).

However it doesn't sound like a very sensible thing to do. You'd be better off writing code to deal with the contents of the json object, rather than trying to run code embedded in the json.

Comments

0

Neither way is particularly nice, but if you can get rid of the function(e) wrapper bits, then you can use var myDynamicFunction = new Function("e", "alert(e);"); Otherwise, you're looking at using eval(). Eval() is evil in general. If this is JSON that you're getting back from a $.getJSON call or something, you're opening yourself up to security concerns.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.