I’m trying to serialize a JavaScript object to json, to be deserialized later back into its original form.
The hard part is that it’s not just primitives I need to serialize. For example:
function Foo() {
this.bar = "Hello World";
}
Foo.prototype.baz = function() {
alert(this.bar);
}
var qux = new Foo();
How would I serialize qux? If I simply JSON.stringify then JSON.parse it, I wouldn’t be able to call qux.baz().
Are there any standards or tools or techniques out there to do this? Any tips to point me in the right direction?
Thanks.
Unfortunately you cannot serialize your complete object to JSON since the JSON spec does not allow functions to be serialized.
You can however create your own serialization standard. You can call it Javascript Frozen Object (JSFO) which is a good name since in other languages what you’re trying to do is usually called “freezing”. Or if you want a name similar to JSON you can call it Javascript Frozen (or Full?) Object Notation (JSFON).
The implementation is fairly straightforward. You can copy the JSON code from any of the libraries that implement it like jQuery or YUI. Or you can download any of the reference implementation from json.org and modify it to stringify functions as well.
To stringify functions you basically need to do something like this:
plug something like that into any of the JSON stringification libraries.
But please don’t call it JSON since JSON is a very specific data format with a published specification.