Serialize Objects in JavaScript
Aug2809Aug 28, 09
I recently needed to store user preferences for a JavaScript application (on amoebaOS) in a file. Since JavaScript's support for XML is not amazing and XML in general is just an under-performing format for data storage (in my opinion), I opted for a JSON-encoded string as a means of storing the preferences. I know there are many libraries out there that might have this same functionality (I believe this is implemented in JSON.stringify), I felt like it would be a chance to post my version of a JavaScript Object serialization method for the masses.
The goal was to have this code working perfectly without doing any intermediary testing, and that's what I did. The unserialize method is not elegant, but it's simpler than parsing manually and still safer than running a standard eval - you'll notice the dangerous global objects (or those that I could think of off the top of my head) are not available because the TinyJSON object declares internal variables that take precedence.
var TinyJSON = (function(){
var window,top,self,parent,location,reload,back,forward,
alert,confirm,prompt,stop,frames,document;
function addslashes(t){
return t.replace(/(\\*)'/gim,"$1$1\\'");
}
function strval(v) {
switch((v.constructor.name+"").toLowerCase()) {
case "number":
return v+0;
break;
case "string":
return "'" + addslashes(v).replace(/\r?\n/gim,'\\n') + "'";
break;
case "date":
return "date("+v.getTime()+")";
break;
case "boolean":
return v===true?"true":"false";
break;
case "array":
var t = "[";
for(var i=0; i<v.length; i++) {
t += strval(v[i]) + ",";
}
return t.replace(/\,$/,'')+"]";
break;
case "object":
return branch(v);
break;
default:
return "null";
break;
}
}
function branch(obj) {
var t = "{";
for(var n in obj) {
t += "\"" + n + "\":" + strval(obj[n]) + ",";
}
return t.replace(/\,$/,'')+"}";
}
var self = {
serialize : function(obj) {
return branch(obj);
},
unserialize : function(str) {
function date(s) {
var d = new Date();
d.setTime(s+0);
return d;
}
return eval('(' + str + ')');
}
};
return self;
})();
You can serialize a JavaScript Object to its string representation as follows:
var obj = {
type : "myObj",
data : [
123456,
new Date()
],
fun : true,
going : 11,
parent : {
type : "parentObj"
}
};
var str = TinyJSON.serialize( obj );
You can convert a TinyJSON string back to object form as follows:
var str = "{\"type\":'myObj',\"data\":[123456,date(1251442681016)], ☟
\"fun\":true,\"going\":11,\"parent\":{\"type\":'parentObj'}}";
var obj = TinyJSON.unserialize( str );


