YUI Library Home

Site Search (YDN & YUIBlog):

# YUI Library Examples: JSON Utility: Rebuilding class instances from JSON data

# JSON Utility: Rebuilding class instances from JSON data

This example illustrates one method of serializing and recreating class instances by using the `replacer` and `reviver` parameters to `JSON.stringify` and `JSON.parse` respectively.

View example in new window.

(stringify results here)

### The CaveMan class

For this example, we'll use a class CaveMan, with a property `discovered` that holds a `Date` instance, and a method `getName`.

YAHOO.util.Event.onDOMReady(function () { // set up some shortcuts var Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, JSON = YAHOO.lang.JSON, Demo; function CaveMan(name,discovered) { this.name = name; this.discovered = discovered; }; CaveMan.prototype.getName = function () { return this.name + ", the cave man"; } ...

### Add `freeze` and `thaw` static methods

We'll add the methods responsible for serializing and reconstituting instances to the CaveMan class as static methods.

// Static method to convert to a basic structure with a class identifier CaveMan.freeze = function (cm) { return { _class : 'CaveMan', n : cm.name, d : cm.discovered // remains a Date for standard JSON serialization }; }; // Static method to reconstitute a CaveMan from the basic structure CaveMan.thaw = function (o) { return new CaveMan(o.n, o.d); };

### Reference the methods in replacer and reviver functions

We'll create a `demo.FreezeThaw` namespace to hold our moving parts. In it, we'll add a method to pass to `JSON.stringify` that calls our custom serializer, and another method to pass to `JSON.parse` that detects the serialized structure and calls our thawing method.

Demo = YAHOO.namespace('demo').FreezeThaw = { cryo : function (k,o) { return (o instanceof CaveMan) ? CaveMan.freeze(o) : o; }, revive : function (k,v) { // Check for cavemen by the _class key if (v instanceof Object && v._class == 'CaveMan') { return CaveMan.thaw(v); } // default to returning the value unaltered return v; } };

### The data to be serialized

We'll create a CaveMan instance and nest it in another object structure to illustrate how the thawing process still operates normally for all other data.

Demo.data = { count : 1, type : 'Hominid', specimen : [ new CaveMan('Ed',new Date(1946,6,6)) ] };

### Thawing from the inside out and the `Date` instance

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.

We'll take advantage of this and apply `YAHOO.lang.JSON.stringToDate` to all string values, which will reconstitute Date instances when they match the iso8601 UTC format that JSON serializes Dates to by default.

Demo = YAHOO.namespace('demo').FreezeThaw = { cryo : function (k,o) { return (o instanceof CaveMan) ? CaveMan.freeze(o) : o; }, revive : function (k,v) { // JSON.stringToDate turns strings in the iso8601 UTC format into Dates if (typeof v === 'string') { return JSON.stringToDate(v); } // Check for cavemen by the _class key if (v instanceof Object && v._class == 'CaveMan') { return CaveMan.thaw(v); } // default to returning the value unaltered return v; } };

Now when the reviver function is evaluating the object it determines to be a CaveMan, the `discovered` property is correctly containing a `Date` instance.

### Choose your serialization

You'll note there are two freeze and thaw operations going on in this example. One for our CaveMan class and one for `Date` instances. Their respective serialization and recreation techniques are different. You are free to decide the serialized format of your objects. Choose whatever makes sense for your application.

### Show and Tell

Now we add the event handlers to the example buttons to call `JSON.stringify` and `parse` with our `example.cryo` and `example.revive` methods, respectively.

Event.on('demo_freeze','click',function (e) { Demo.jsonString = JSON.stringify(Demo.data, Demo.cryo); Dom.get('demo_frozen').value = Demo.jsonString; Dom.get('demo_thaw').disabled = false; }); Event.on('demo_thaw','click',function (e) { var x = JSON.parse(Demo.jsonString, Demo.revive); cm = x.specimen[0]; Dom.get('demo_thawed').innerHTML = "<p>Specimen count: " + x.count + "</p>"+ "<p>Specimen type: " + x.type + "</p>"+ "<p>Instanceof CaveMan: " + (cm instanceof CaveMan) + "</p>"+ "<p>Name: " + cm.getName() + "</p>"+ "<p>Discovered: " + cm.discovered + "</p>"); }); }); // end of onDOMReady handler

### Full Code Listing

YAHOO.util.Event.onDOMReady(function () { var Event = YAHOO.util.Event, Dom = YAHOO.util.Dom, JSON = YAHOO.lang.JSON, Demo; Demo = YAHOO.namespace('demo').FreezeThaw = { data : null, jsonString : null, cryo : function (k,o) { return (o instanceof CaveMan) ? CaveMan.freeze(o) : o; }, revive : function (k,v) { // Turn anything that looks like a UTC date string into a Date instance if (typeof v === 'string') { return JSON.stringToDate(v);; } // Check for cavemen by the _class key if (v instanceof Object && v._class == 'CaveMan') { return CaveMan.thaw(v); } // default to returning the value unaltered return v; } }; function CaveMan(name,discovered) { this.name = name; this.discovered = discovered; }; CaveMan.prototype.getName = function () { return this.name + ", the cave man"; } // Static methods to convert to and from a basic object structure CaveMan.thaw = function (o) { return new CaveMan(o.n, o.d); }; // Convert to a basic object structure including a class identifier CaveMan.freeze = function (cm) { return { _class : 'CaveMan', n : cm.name, d : cm.discovered // remains a Date for standard JSON serialization }; }; Demo.data = { count : 1, type : 'Hominid', specimen : [ new CaveMan('Ed',new Date(1946,6,6)) ] }; Event.on('demo_freeze','click',function (e) { Demo.jsonString = JSON.stringify(Demo.data, Demo.cryo); Dom.get('demo_frozen').value = Demo.jsonString; Dom.get('demo_thaw').disabled = false; }); Event.on('demo_thaw','click',function (e) { var parsedData = JSON.parse(Demo.jsonString, Demo.revive); cm = parsedData.specimen[0]; Dom.get('demo_thawed').innerHTML = "<p>Specimen count: " + parsedData.count + "</p>"+ "<p>Specimen type: " + parsedData.type + "</p>"+ "<p>Instanceof CaveMan: " + (cm instanceof CaveMan) + "</p>"+ "<p>Name: " + cm.getName() + "</p>"+ "<p>Discovered: " + cm.discovered + "</p>"; }); });

## Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

### YUI Logger Output:

Note: Logging and debugging is currently turned off for this example.

Reload with logging
and debugging enabled.

### JSON Utility Examples:

### More JSON Utility Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2010 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings