the json format cannot represent functions like that (directly). you could encode it as a string and then instantiate the function explicitly in the client, or pass the name of a function that's already present at the client.


from json format definition here it is clear that you cannot have functions in json.

define your function elsewhere in application and call it explicitly.

any kind of hack to support functions in json is bad practice as it conflicts with purpose of json as "lightweight data-interchange format". you can't interchange functions as they cannot be understood by anything else except javascript.


i was trying to accomplish something similar. in my case i was using mvc razor syntax trying to generate a json object with a function passed in using the @<text> syntax.

i was able to get the desired output using the library (using jsonconvert and jraw).


public class jsobj
    public string title { get; set; }
    public int upperval { get; set; }
    public int lowerval { get; set; }
    public object mouseover
            // use jraw to set the value of the anonymous function
            return new jraw(string.format(@"function(){{ return {0}; }}", upperval - lowerval));

// and then serialize using the jsonconvert class
var obj = new jsobj { title = "test", lowerval = 4, upperval = 10 };
var jsonobj = jsonconvert.serializeobject(obj);

that should get you the json object with the function (instead of the function in a string).

{"title":"test","upperval":10,"lowerval":4,"mouseover":function(){ return 6; }}

post: how to serialize a function to json (using razor @<text>)

Related Query

More Query from same tag