YUI 3.x Home -

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

JSON: 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.

(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.

  1. YUI({base:"../../build/", timeout: 10000}).use("node", "json", function(Y) {
  2.  
  3. function CaveMan(name,discovered) {
  4. this.name = name;
  5. this.discovered = discovered;
  6. };
  7. CaveMan.prototype.getName = function () {
  8. return this.name + ", the cave man";
  9. }
  10.  
  11. ...
YUI({base:"../../build/", timeout: 10000}).use("node", "json", function(Y) {
 
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.

  1. // Static method to convert to a basic structure with a class identifier
  2. CaveMan.freeze = function (cm) {
  3. return {
  4. _class : 'CaveMan',
  5. n : cm.name,
  6. d : cm.discovered // remains a Date for standard JSON serialization
  7. };
  8. };
  9.  
  10. // Static method to reconstitute a CaveMan from the basic structure
  11. CaveMan.thaw = function (o) {
  12. return new CaveMan(o.n, o.d);
  13. };
// 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 an example 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.

  1. var example = {
  2. cryo : function (k,o) {
  3. return (o instanceof CaveMan) ? CaveMan.freeze(o) : o;
  4. },
  5.  
  6. revive : function (k,v) {
  7. // Check for cavemen by the _class key
  8. if (v instanceof Object && v._class == 'CaveMan') {
  9. return CaveMan.thaw(v);
  10. }
  11. // default to returning the value unaltered
  12. return v;
  13. }
  14. };
var example = {
    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.

  1. example.data = {
  2. count : 1,
  3. type : 'Hominid',
  4. specimen : [
  5. new CaveMan('Ed',new Date(1946,6,6))
  6. ]
  7. };
example.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 by watching for UTC formatted date strings (the default JSON serialization for Dates) and reviving them into proper Date instances before the containing object gets its turn in the reviver.

  1. var example = {
  2. dateRE : /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/,
  3.  
  4. cryo : function (k,o) {
  5. return (o instanceof CaveMan) ? CaveMan.freeze(o) : o;
  6. },
  7. revive : function (k,v) {
  8. // Turn anything that looks like a UTC date string into a Date instance
  9. var match = Y.Lang.isString(v) ? v.match(example.dateRE) : null,
  10. d;
  11.  
  12. if (match) {
  13. d = new Date();
  14. d.setUTCFullYear(match[1], (match[2] - 1), match[3]);
  15. d.setUTCHours(match[4], match[5], match[6]);
  16. return d;
  17. }
  18. // Check for cavemen by the _class key
  19. if (v instanceof Object && v._class == 'CaveMan') {
  20. return CaveMan.thaw(v);
  21. }
  22. // default to returning the value unaltered
  23. return v;
  24. }
  25. };
var example = {
    dateRE : /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/,
 
    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
        var match = Y.Lang.isString(v) ? v.match(example.dateRE) : null,
            d;
 
        if (match) {
            d = new Date();
            d.setUTCFullYear(match[1], (match[2] - 1), match[3]);
            d.setUTCHours(match[4], match[5], match[6]);
            return d;
        }
        // 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 very different. You are free to decide the serialized format of your objects. Choose whatever makes sense for your application.

Note: There is no explicit Date serialization method listed inline because JSON natively supports Date serialization. However, it is outside the scope of the parser's duty to create Date instances, so it's up to you to recreate them in the parse phase. Feel free to use the method included here.

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.

  1. Y.one('#demo_freeze').on('click',function (e) {
  2. example.jsonString = Y.JSON.stringify(example.data, example.cryo);
  3.  
  4. Y.one('#demo_frozen').set('innerHTML', example.jsonString);
  5. Y.one('#demo_thaw').set('disabled',false);
  6. });
  7.  
  8. Y.one('#demo_thaw').on('click',function (e) {
  9. var x = Y.JSON.parse(example.jsonString, example.revive);
  10. cm = x.specimen[0];
  11.  
  12. Y.one('#demo_thawed').set('innerHTML',
  13. "<p>Specimen count: " + x.count + "</p>"+
  14. "<p>Specimen type: " + x.type + "</p>"+
  15. "<p>Instanceof CaveMan: " + (cm instanceof CaveMan) + "</p>"+
  16. "<p>Name: " + cm.getName() + "</p>"+
  17. "<p>Discovered: " + cm.discovered + "</p>");
  18. });
  19.  
  20. }); // end of YUI(..).use(.., function (Y) {
Y.one('#demo_freeze').on('click',function (e) {
    example.jsonString = Y.JSON.stringify(example.data, example.cryo);
 
    Y.one('#demo_frozen').set('innerHTML', example.jsonString);
    Y.one('#demo_thaw').set('disabled',false);
});
 
Y.one('#demo_thaw').on('click',function (e) {
    var x  = Y.JSON.parse(example.jsonString, example.revive);
        cm = x.specimen[0];
 
    Y.one('#demo_thawed').set('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 YUI(..).use(.., function (Y) {

Full Code Listing

  1. YUI({base:"../../build/", timeout: 10000}).use("node", "json", function(Y) {
  2.  
  3. var example = {
  4. data : null,
  5. jsonString : null,
  6.  
  7. dateRE : /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/,
  8.  
  9. cryo : function (k,o) {
  10. return (o instanceof CaveMan) ? CaveMan.freeze(o) : o;
  11. },
  12. revive : function (k,v) {
  13. // Turn anything that looks like a UTC date string into a Date instance
  14. var match = Y.Lang.isString(v) ? v.match(example.dateRE) : null,
  15. d;
  16.  
  17. if (match) {
  18. d = new Date();
  19. d.setUTCFullYear(match[1], (match[2] - 1), match[3]);
  20. d.setUTCHours(match[4], match[5], match[6]);
  21. return d;
  22. }
  23. // Check for cavemen by the _class key
  24. if (v instanceof Object && v._class == 'CaveMan') {
  25. return CaveMan.thaw(v);
  26. }
  27. // default to returning the value unaltered
  28. return v;
  29. }
  30. };
  31.  
  32. function CaveMan(name,discovered) {
  33. this.name = name;
  34. this.discovered = discovered;
  35. };
  36. CaveMan.prototype.getName = function () {
  37. return this.name + ", the cave man";
  38. }
  39.  
  40. // Static methods to convert to and from a basic object structure
  41. CaveMan.thaw = function (o) {
  42. return new CaveMan(o.n, o.d);
  43. };
  44. // Convert to a basic object structure including a class identifier
  45. CaveMan.freeze = function (cm) {
  46. return {
  47. _class : 'CaveMan',
  48. n : cm.name,
  49. d : cm.discovered // remains a Date for standard JSON serialization
  50. };
  51. };
  52.  
  53. example.data = {
  54. count : 1,
  55. type : 'Hominid',
  56. specimen : [
  57. new CaveMan('Ed',new Date(1946,6,6))
  58. ]
  59. };
  60.  
  61. Y.one('#demo_freeze').on('click',function (e) {
  62. example.jsonString = Y.JSON.stringify(example.data, example.cryo);
  63.  
  64. Y.one('#demo_frozen').set('innerHTML', example.jsonString);
  65. Y.one('#demo_thaw').set('disabled',false);
  66. });
  67.  
  68. Y.one('#demo_thaw').on('click',function (e) {
  69. var parsedData = Y.JSON.parse(example.jsonString, example.revive);
  70. cm = parsedData.specimen[0];
  71.  
  72. Y.one('#demo_thawed').set('innerHTML',
  73. "<p>Specimen count: " + parsedData.count + "</p>"+
  74. "<p>Specimen type: " + parsedData.type + "</p>"+
  75. "<p>Instanceof CaveMan: " + (cm instanceof CaveMan) + "</p>"+
  76. "<p>Name: " + cm.getName() + "</p>"+
  77. "<p>Discovered: " + cm.discovered + "</p>");
  78. });
  79.  
  80. // Expose the example objects for inspection
  81. example.CaveMan = CaveMan;
  82. YUI.example = example;
  83.  
  84. });
YUI({base:"../../build/", timeout: 10000}).use("node", "json", function(Y) {
 
var example = {
    data       : null,
    jsonString : null,
 
    dateRE : /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/,
 
    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
        var match = Y.Lang.isString(v) ? v.match(example.dateRE) : null,
            d;
 
        if (match) {
            d = new Date();
            d.setUTCFullYear(match[1], (match[2] - 1), match[3]);
            d.setUTCHours(match[4], match[5], match[6]);
            return d;
        }
        // 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
    };
};
 
example.data    = {
    count : 1,
    type  : 'Hominid',
    specimen : [
        new CaveMan('Ed',new Date(1946,6,6))
    ]
};
 
Y.one('#demo_freeze').on('click',function (e) {
    example.jsonString = Y.JSON.stringify(example.data, example.cryo);
 
    Y.one('#demo_frozen').set('innerHTML', example.jsonString);
    Y.one('#demo_thaw').set('disabled',false);
});
 
Y.one('#demo_thaw').on('click',function (e) {
    var parsedData = Y.JSON.parse(example.jsonString, example.revive);
        cm = parsedData.specimen[0];
 
    Y.one('#demo_thawed').set('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>");
});
 
// Expose the example objects for inspection
example.CaveMan = CaveMan;
YUI.example = example;
 
});

Copyright © 2009 Yahoo! Inc. All rights reserved.

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