Reconstitute JSON

by danielzen

JavaScript

function Glove(material, color) {
  this.material = material;
  this.color = color;
  this._type = "Glove";
}

Glovebox.prototype = [];
Glovebox.prototype.constructor = Glovebox;
function Glovebox(name) {
  this.name = name;
  this._type = "Glovebox"
};

Glovebox.prototype.howMany = function() {
  console.log("Has "+ this.length+" pairs in box");
};

var pair1 = new Glove("leather", "red");
var pair2 = new Glove("cotton", "black");

var box = new Glovebox();
box.push(pair1);
box.push(pair2);

var jsonString = JSON.stringify(box);
console.log(box); 
box.howMany();    

var jsonObj = JSON.parse(jsonString);
var box2 = eval("new "+jsonObj._type);
jQuery.extend(box2, jsonObj);   
for(var name in box2) {
    var elem = box2[name];
    console.log(name+":"+elem);
    if (typeof elem !== "undefined" && typeof elem._type !== "undefined") {
        console.log("yes:"+name);
        var newElem = eval("new "+elem._type); //Security hole
        jQuery.extend(newElem, elem);   
        box2[name] = newElem;
    }
}
console.log(box2);   
box2.howMany();