Serialize Objects in JavaScript

Aug2809Aug 28, 09

Author's note: This is a simplification, and it is not recommended for use in public projects. The de-facto JSON library is written by Douglas Crockford, and is available at

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 (JSON.stringify), I felt like it would be a chance to post my simplification 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,
	function addslashes(t){
		return t.replace(/(*)'/gim,"$1$1'");
	function strval(v) {
		switch(("").toLowerCase()) {
			case "number":
				return v+0;
			case "string":
				return "'" + addslashes(v).replace(/r?n/gim,'n') + "'";
			case "date":
				return "date("+v.getTime()+")";
			case "boolean":
				return v===true?"true":"false";
			case "array":
				var t = "[";
				for(var i=0; i<v.length; i++) {
					t += strval(v[i]) + ",";
				return t.replace(/,$/,'')+"]";
			case "object":
				return branch(v);
				return "null";
	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();
				return d;
			return eval('(' + str + ')');
	return self;

You can serialize a JavaScript Object to its string representation as follows:

var obj = {
	type : "myObj",
	data : [
		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)], 
var obj = TinyJSON.unserialize( str );

About Jason Miller:

I am a JavaScript developer from Waterloo, Ontario, Canada. When I am not typing green code onto a black screen, you might find me at the nearest coffee pub checking out the brew. I run a internet firm called developIT and maintain blogs and web apps when I can.
cheap jordans#
Leave a Comment

Post Comment