views:

65

answers:

2

Is there a function or library that will take a JS Object that has properties and functions and stringify it to JSON but when it comes to a Function, it will change it into a property and call the function to return its value??

function object() {
    this.property = 12;
    this.function = function() { return "This"; }
} 

So this would stringify into:

{property: 12, function: "This"}

Any ideas? Just curious if there is one already.. if not I will take a stab at one. It shouldn't be to hard to extend a JSON.stringify().

A: 

Some objects have no trivial serialization. If you wish you serialize them, you must do so yourself with you own set of assumptions.

Functions (esp. those with closures) and IO Streams are some examples. In the case of a JS function, serialization (without serializaing the entire context!) violates the semantics of the function with respect to the execution context and scope chains. Also, the ability for assistance from the browser to return the "text" of a function depends upon the browser.

pst
+1  A: 

The JSON.stringify method provides the option to include a callback argument, called replacer, the function is invoked passing the key and value of each property of your object, there you are able to detect if the value is a function and invoke it:

var obj = {
  "property": 12,
  "function": function() { return "This"; }
};

JSON.stringify(obj, function (key, value) {
  if (typeof value == 'function') {
    return value();
  }
  return value;
});
CMS
This almost worked. It doesn't seem to call the callback() if it is a function. It seems as if the stringify code excludes those automatically. So I will/would have to just modify the JSON code to have it call into the callback if one is detected.Great find!
James Armstead
@James, Thanks, oh, I forgot to tell you that Firefox 3.6 has an [implementation bug](http://skysanders.net/subtext/archive/2010/02/24/confirmed-bug-in-firefox-3.6-native-json-implementation.aspx) using this `replacer` argument. Another option would be to implement your custom `stringify` function, something like [this](http://github.com/remy/console/blob/master/console.js#L4).
CMS