Make javascript object serialization a snap! Have you found JSON.stringify and JSON.parse insufficient? HydrateJS may be what you're looking for.
Note: designed mainly for browsers, but may have a place with server-side code as well. Untested though.
Native JSON serialization (via JSON.stringify) is convenient, but has a couple critical pitfalls:
- If your Javascript object is actually an instance of something other than a hash ({}), this information is lost when serializing -- so a method that may have existed pre-serialization on an object won't exist post-deserialization.
- Another problem is circular references -- they simply don't work (JSON will throw an exception).
- Lastly, object references -- i.e. two elements in an array that point to the exact same object -- aren't deserialized as one might expect.
HydrateJS aims to fix all those.
Dependencies
Only json2.js, but this is bundled with HydrateJS and automatically required into the page as needed.
Install
- Option 1: Download pre-compiled JS from here.
- Option 2: HydrateJS is written in CoffeeScript, a new spiffy language that compiles down to JavaScript. You can get started here: http://www.coffeescript.com/. (you'll need to install Node and npm if you haven't already, but that should take no more than 5 minutes). Then run ./compile.sh.
Limitations
Due to the nature of JavaScript, there are some limitations in order to make serialization work.
-
Can't use anonymous functions as constructors.
Reason: to identify the constructor used to build an object, the framework uses the constructor's #name property. Anonymous functions have a blank name.
-
Can't attach functions to instances. This is part of the general "can't serialize functions" rule, and even if you could, I'm pretty sure it'd cause more problems than solve. I know this doesn't work well with certain Javascript patterns out there, but since the Person constructor would never get called on the deserialized object, there's no way we could attach #getName to the deserialized instance. We can't call the constructor on the instance either because a) we don't know what args to pass in, and b) it may have other undesirable side effects.
-
Can't write to the "constructor" property of an object. In order to deserialize an object, we must know what its constructor was (and more importantly, the constructor's prototype object). The only way to do this is by taking the constructor property from the to-be-serialized object.
License
MIT license -- do what you want.
Authors
Max Aller (nanodeath@gmail.com)
Contact
Max Aller (nanodeath@gmail.com)
Download
You can download this project in either
zip or
tar formats.
You can also clone the project with Git
by running:
$ git clone git://github.com/nanodeath/HydrateJS