campino2k campino2k - 1 year ago 103
Javascript Question

Is there any possibility to have JSON.stringify preserve functions?

Take this object:

x = {
"key1": "xxx",
"key2": function(){return this.key1}

If I do this:

y = JSON.parse( JSON.stringify(x) );

Then y will return
{ "key1": "xxx" }
. Is there anything one could do to transfer functions via stringify? Creating an object with attached functions is possible with the "ye goode olde eval()", but whats with packing it?

Answer Source

You can't pack functions since the data they close over is not visible to any serializer. Even Mozilla's uneval cannot pack closures properly.

Your best bet, is to use a reviver and a replacer.

The reviver function passed to JSON.parse is applied to all key:value pairs in the raw parsed object from the deepest keys to the highest level. In our case, this means that the name and discovered properties will be passed through the reviver, and then the object containing those keys will be passed through.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download