Justin Rassier
Justin Rassier

Reputation: 908

jQuery.ParseJSON() to include function reference

I have a callback function within an ASP.NET Web Forms application which I am trying to return some handy JSON to so that the javascript function manage the data. I am able to send back a string of JSON that contains all of my data, but now I am trying to get the following structure:

{
 data: dataGoesHere
 function: function(){alert('hello');}
}

jQuery.parseJSON works great for the simple case of a string being returned like this:

"{\"data\" : \"dataGoesHere\"}"

but soon as you try to do something like this

"{
   \"data\" : \"dataGoesHere\"
   \"function" function(){alert('hello');}
}"

jQuery throws an exception. I am wondering if it is possible to create a string so that jQuery can parse into JSON that will include a function reference that I can call later.

I hope this makes sense. Thank you for your time and responses!

Upvotes: 2

Views: 2836

Answers (3)

QuinnG
QuinnG

Reputation: 6424

You could set up it up as valid JSON and use eval.

Edit: j = jQuery.parseJSON("{\"data\":\"DataGoesHere\",\"function\":\"{alert('test');}\"}");

eval(j.function)

Upvotes: 0

user113716
user113716

Reputation: 322492

You can do it like this:

Example: http://jsfiddle.net/MvRru/

var jsonStr = '{"data" : "dataGoesHere","fn": "{alert(\'hello\');}"}';

var result = $.parseJSON( jsonStr );

result.fn = new Function( result.fn );

result.fn();

Upvotes: 0

SLaks
SLaks

Reputation: 887433

That's not valid JSON.
It's rejected by jQuery for security reasons, in order to prevent exactly what you're trying to do.

Instead, you can just call eval, to interpret it as a Javascript literal.
Note that you'll need to wrap it in parentheses to make sure that it's parsed as an expression and not a block.

Upvotes: 4

Related Questions