vtortola vtortola - 2 months ago 5
JSON Question

Getting JSON with functions with jQuery

In the root of my

file I declare:

var Doe = {
"foo": "The quick brown fox jumps over the lazy dog.",
"bar": "ABCDEFG",
"baz": [52, 97],
"testfunc": function(){alert('json function');}

And in my HTML:

<a id="lele" href="javascript:void(0)" onclick="Doe.testfunc()">Doe</a>

And when I click it it works, so I know it's possible to put functions in JSON objets.

Now, in the root of the
I declare:

$.getJSON("~/rule/2", function(data) {
alert("2: " + data.foo);

And the server is returning this for that url:

context.Response.ContentType = "application/json";
""foo"": ""The quick brown fox jumps over the lazy dog."",
""bar"": ""ABCDEFG"",
""baz"": [52, 97],
""testfunc"": function(){alert('json function');}

But nothing happens :( Aparently because if there is an error, .getJSON will fail silently. But, if I remove the lines regarding of the function:

$.getJSON("~/rule/2", function(data) {
alert("2: " + data.foo);


""foo"": ""The quick brown fox jumps over the lazy dog."",
""bar"": ""ABCDEFG"",
""baz"": [52, 97]}");

Then it works, an alert pop up with the content of the "foo" property.

What is the problem with the function? :( In the moment that I put a function in the JSON object, jQuery fails.

Kind regards.


You don't have a JSON object.

You have an object literal. Functions cannot be values of a JSON string.

JSON is only a subset of the object literal syntax. Possible values are:


Read more on json.org

This is JavaScript object:

var foo = {bar: 42}

and this is a JSON string:

var foo = '{"bar": 42}';

See also JavaScript, JSON objects and object literal notation.

Update: In order to return and execute JavaScript, you can do the following:

You can return plain JavaScript e.g.

context.Response.ContentType = "text/javascript";
 function testfunc(){
     alert('json function')

and use $.ajax with dataType: 'script':

    url: "~/rule/2",
    dataType: 'script',
    success: function(data) {}


You can also define JavaScript objects with functions like so:

context.Response.ContentType = "text/javascript";
     var obj = {
         bar: function(){alert(42);}

You just need to have a global function called yourHandler (and of course still call ajax with dataType: script).

This is probably what comes closest to what you want. The difference is, that you don't return JSON, but JavaScript, and you don't process the object in the success callback, but in another function, which has to be called from within the JS you sent.

See another DEMO