JSON-Serialize.js provides conventions and helpers to manage serialization and deserialization of instances to/from JSON.
Download Latest (1.1.3):
Please see the release notes for upgrade pointers.
Module Loading
JSON-Serialize.js is compatible with RequireJS, CommonJS, Brunch and AMD module loading. Module names:
- 'json-serialize' - json-serialize.js.
Examples
- JSON-Serialize natively supports nested Date serialization so this "just works":
var embedded_date_objects = to: from: 1 ; var json = JSON;var deserialized_embedded_date_objects = JSON;
Pretty cool, eh?
- Creating custom serialization for one of your classes.
: this.int_value = int_value; this.string_value = string_value; this.date_value = date_value; : -> return _type:'SomeClass' int_value:thisint_value string_value:thisstring_value date_value:JSONserializethisdate_value : # note: this is a class method if json_type!='SomeClass' return null; return jsonint_valuejsonstring_valueJSONdeserializejsondate_value;
Now you can automatically serialize and deserialize it:
instance = 1'two';json = JSONserializeinstance # this calls the toJSON function on the instance instance2 = JSONdeserializejson # this calls the fromJSON function on the class (you need to make sure the constructor can be found)
Conventions
Uses the following configurable conventions:
- use a '_type" field in the json that you serialize
- for serializing, implement a toJSON function as an instance method.
- for deserializing, implement a fromJSON deserialization factory function as an class method. This doesn't need to be a class function but can be any function as long as it can be found (see JSON.deserialize.NAMESPACE_ROOTS).
Options
- JSON.deserialize.TYPE_FIELD
You can globally choose the type field used when deserializing an instance from JSON.
For example, if you use couchdb, you could use a 'type' field convention:
JSON.deserialize.TYPE_FIELD = 'type'
- JSON.deserialize.NAMESPACE_ROOTS
If you don't want to pollute the global namespace with your deserialization factory functions, you can put them in any sort of nested namespaces. Just register your namespace roots like:
JSONdeserializeNAMESPACE_ROOTSpushwindowmy_classes
Building, Running and Testing the library
Installing:
- install node.js: http://nodejs.org
- install node packages: 'npm install'