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 json.org/json2.js.

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,
		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 );

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.
Comments
oakleysunglasses#
http://www.oakleyvault.us.com/
http://www.oakley--sunglasses.com.co/
http://www.oakleysunglassesoutlet.us.org/
http://www.oakleysunglasses.us.com/
http://www.oakleysunglasses.com.co/
http://www.rayban-sunglass.us.com/
http://www.ray-ban-sunglass.us.com/
http://www.rayban--sunglasses.org/
http://www.polo-ralph-lauren.us.com/
http://www.polo-ralph-lauren-outlet.us.com/
http://www.burberry-outlet-store.us.com/
http://www.burberryoutlet-store.us.com/
http://www.michaelkors-outlet-online.us.org/
http://www.outletonline-michaelkors.com/
http://www.michaelkors-outlet-online.us.com/
http://www.michael-korsoutlet.in.net/
http://www.michaelkors-outlet-store.us.com/
http://www.michaelkors-handbags.in.net/
http://www.uggs-outletboots.in.net/
http://www.uggsoutlet.us.com/
http://www.uggs-outlet.in.net/
http://www.cheapuggboots.in.net/
http://www.cheap-uggs.in.net/
http://www.louisvuitonoutlet.us.com/
http://www.louisvuitton-outlets.org/
http://www.louisvuitton.ar.com/
http://www.louisvuitton-outlet-store.com/
http://www.louis-vuittonhandbags.org/
http://www.redbottoms.in.net/
http://www.christianlouboutin-outlet.in.net/
http://www.christian-louboutin-shoes.in.net/
http://www.christian-louboutin.org.uk/
http://www.rolexreplicawatches.us.com/
http://www.replica--watches.com/
http://www.air-jordanshoes.net/
http://www.nike--outlet.com/
http://www.toryburch-outletonline.in.net/
http://www.guccioutlet-online.us.com/
http://www.prada-handbags.us.com/
http://www.prada-outlets.in.net/
http://www.longchamp-outlet.in.net/
http://www.longchamphandbags.in.net/
http://www.longchamphandbagsoutlet.us.com/
http://www.tiffany-and-co.us.com/
http://www.tiffanyjewelry.us.com/
http://www.nikeairmaxinc.net/
http://www.nikeair-max.net/
http://www.nike-freerun.com/
http://www.chanel-handbags-outlet.in.net/
http://www.katespadeoutlets.cc/
http://www.katespade-handbags.in.net/
http://www.coachoutlet-online.in.net/
http://www.coachfactory-outletonline.in.net/
http://www.coachoutletstoreonline.jp.net/
http://www.coachpurse.in.net/
http://www.true-religionoutlet.in.net/
http://www.truereligionjeansoutlet.us.com/
http://www.truereligionoutlets.in.net/
http://www.cheaptruereligion.us.com/
http://www.nike-airmax-pas-cher.fr/
http://www.nikeair-max.fr/
http://www.airjordanpas-cher.fr/
http://www.nikefreerun.fr/
http://www.nike-roshe-run.fr/
http://www.sac-longchamp-pas-cher.fr/
http://www.sac--longchamps.fr/
http://www.poloralphlauren-pascher.fr/
http://www.louboutin-pas-chere.fr/
http://www.sac-michaelkors-pascher.fr/
http://www.sac-burberry-pascher.fr/
http://www.lunette-oakley-pascher.fr/
http://www.lunette-rayban-pas-cher.fr/
http://www.hollister-abercrombiefitch.fr/
http://www.sachermes.fr/
http://www.vanspas-cher.fr/
http://www.timberland-paschere.fr/
http://www.newbalancesoldes.fr/
http://www.converse-pas-cher.fr/
http://www.the-north-face.fr/
http://www.niketnrequin-pascher.fr/
http://www.polo-lacoste-pascher.fr/
http://www.nikeblazerpaschere.fr/
http://www.nikeair-force.fr/
http://www.sac-guesspascher.fr/
http://www.sac-vanessa-bruno.fr/
http://www.scarpehogan--outlet.it/
http://www.rayban-sunglasses.me.uk/
http://www.michaelkorshandbags-uk.org.uk/
http://www.michaelkors-outlet-canada.ca/
http://www.michael--korsoutlet.ca/
http://www.lululemon-outlet-canada.ca/
http://www.hollistersale.org.uk/
http://www.thenorth--face.co.uk/
http://www.mulberryhandbagsoutlet.co.uk/
http://www.ralphlauren-outlet.co.uk/
http://www.nike--airmax.co.uk/
http://www.nikeairmax.org.uk/
http://www.nike-free-run.org.uk/
http://www.abercrombie-and-fitch.org.uk/
http://www.nike-roshe-run.org.uk/
http://www.nike-trainers.org.uk/
http://www.nike-air-huarache.co.uk/
http://www.longchampbags.org.uk/
http://www.hollister-abercrombie.es/
http://www.vans-shoes-outlet.com/
http://www.nikerosherun.net/
http://www.maccosmeticsoutlet.us/
http://www.abercrombie-andfitch.us.com/
http://www.hermesbirkinbags.com.co/
http://www.the-northfaceoutlet.us.com/
http://www.the-north-face.in.net/
http://www.newbalance-shoes.in.net/
http://www.reebok-outlet.in.net/
http://www.lululemonoutlets.in.net/
http://www.cheap-nfljersey.in.net/
http://www.cheap-wedding-dresses.org/
http://www.beatsbydrdreheadphones.in.net/
http://www.montblanc-pens.us.com/
http://www.ferragamo-shoes.net/
http://www.giuseppe-zanotti.in.net/
http://www.instylerionicstyler.us.com/
http://www.babyliss.in.net/
http://www.mcm-handbags.net/
http://www.chiflatiron.cn.com/
http://www.insanityworkout.in.net/
http://www.ghdhair-straighteners.org.uk/
http://www.bottegaveneta-handbagsoutlet.com/
http://www.valentino-shoes.us.com/
http://www.herveleger.us/
http://www.asicso.com/
http://www.soccer--shoes.net/
http://www.soccerjerseys.com.co/
http://www.celine-handbags.org/
http://www.p90x3workout.us.com/
http://www.jimmychoo-shoes.us.com/
http://www.hollister-clothingstore.us.com/
http://www.nike-airmax.nl/
http://www.baseball-bats.us/
http://www.iphone-cases.us.com/
http://www.ipadcases.us.com/
http://www.iphone6scases.us.com/
http://www.iphone6spluscases.us.com/
http://www.iphone6cases.us.com/
http://www.iphone6pluscases.in.net/
http://www.iphone5scases.us.com/
http://www.samsunggalaxys6cases.us.com/
http://www.timberland-boots.us/
http://www.occhiali-oakley.it/
http://www.christian--louboutin.it/
http://www.ralphlauren-outlet.it/
http://www.abercrombiehollister.it/
http://www.nikeair-max.it/
http://www.vansscarpe.it/
http://www.converse-allstar.it/
http://www.borse--gucci.it/
http://www.rayban--occhiali.it/
http://www.converse--shoes.com/
http://www.saclancelpascher.fr/
http://www.toms--shoes.net/
http://www.montrespas-cher.fr/
http://www.karenmillen.me.uk/
http://www.supra--shoes.com/
http://www.juicycoutureoutlet.jp.net/
http://www.juicycoutureoutlet.com.co/
http://www.marcjacobs.us.org/
http://www.cheapweddingdresses.org.uk/
http://www.replica--watches.co.uk/
http://www.hollister--canada.ca/
http://www.pandora-jewelry.us.com/
http://www.pandorajewelrys.us.com/
http://www.pandora--charms.in.net/
http://www.pandora--charms.org.uk/
http://www.linksoflondon.me.uk/
http://www.thomas-sabo-uk.org.uk/
http://www.swarovski-jewelry.in.net/
http://www.swarovski.me.uk/
http://www.bottesugg-pas-cher.fr/
http://www.ugg-pas-cher.fr/
http://www.ugg-boots-uggs.co.uk/
http://www.ugg--australia.it/
http://www.uggs-canada.ca/
http://www.louisvuittonpas-cher.fr/
http://www.louisvuitton-sac.fr/
http://www.louis-vuitton-handbags.org.uk/
http://www.louis-vuitton.ca/
http://www.borse-louis-vuitton.it/
http://coachofficialsite.blog.com/
http://www.canadagoose.net.co/
http://www.canada-goose-jackets.us.com/
http://www.canada-goose-outlet.us.com/
http://www.canadagoose--jackets.ca/
http://www.canadagoose-paschere.fr/
http://www.canada-goose.me.uk/
http://www.moncler.org.uk/
http://www.moncleroutlet.com.co/
http://www.monclerjackets.us.org/
http://www.doudoune-monclerpascher.fr/
http://www.barbour-jackets.org.uk/
http://www.moncler--outlet.it/
http://www.canada--goose.se/
http://www.moncleronline-shop.de/
http://www.moncler.org.es/
http://www.moncler.co.nl/
http://www.canadagooses.co.nl/
http://www.barbour.us.org/
http://www.oakleys-glasses.us.com/
http://www.michael-kors-outlet.us.org/
http://www.michaelkorsoutletonline-sale.us.com/
UGG Boots#

[url=http://www.longchampoutletstore.org/][b]Longchamp Outlet[/b][/url]

[url=http://www.nfljerseys.us/][b]NFL Jersey[/b][/url]

[url=http://www.yeezyboost350.us.com/][b]Yeezy Boost 350[/b][/url]

[url=http://www.jordan4.us/][b]Jordan 4[/b][/url]

[url=http://www.nikeoutletsstore.com/][b]Nike Outlets[/b][/url]

[url=http://www.longchampbags.us.com/][b]Longchamp Bags[/b][/url]

[url=http://www.airmax2016.us.com/][b]Nike Air Max 2016[/b][/url]

[url=http://www.adidas-uk.org.uk/][b]Adidas UK[/b][/url]

[url=http://www.nikeoutletfactorystore.com/][b]Nike Outlet[/b][/url]

[url=http://www.underarmouroutlet.us.com/][b]Under Armour[/b][/url]

[url=http://www.timberlanduk.org.uk/][b]Timberland UK[/b][/url]

[url=http://www.jordan12.us/][b]Jordan 12[/b][/url]

[url=http://www.poloralphlaurenoutlets.us.com/][b]Polo Ralph Lauren Outlet[/b][/url]

[url=http://www.yeezy-shoes.us.com/][b]Yeezy[/b][/url]

[url=http://www.nikeoutlet.org.uk/][b]Nike Outlet[/b][/url]

[url=http://www.nikehuarache.us/][b]Nike Huarache[/b][/url]

[url=http://www.kedsshoesforwomen.com/][b]Keds Shoes For Women[/b][/url]

[url=http://www.nikerosherun.us.com/][b]Roshe Run[/b][/url]

[url=http://www.yeezy.com.co/][b]Yeezy Shoes[/b][/url]

[url=http://www.nikeairmax.us/][b]Nike Air Max[/b][/url]

[url=http://www.outletrayban.us/][b]Ray Ban Outlet[/b][/url]

[url=http://www.oakleyoutlet-store.us/][b]Oakley Outlet[/b][/url]

[url=http://www.adidasnmd.us.com/][b]Adidas NMD[/b][/url]

[url=http://www.rayban-outlets.com/][b]Ray Ban Outlet Store[/b][/url]

[url=http://www.cheap--jordanshoes.us.com/][b]Cheao Jordan Shoes[/b][/url]

[url=http://www.outlettoms.us/][b]Toms Outlet[/b][/url]

[url=http://www.ultraboostuncaged.us/][b]Ultra Boost Uncaged[/b][/url]

[url=http://www.mlb-jerseys.us/][b]MLB Jerseys[/b][/url]

[url=http://www.uggboots-outlets.com/][b]Ugg Boots Outlet[/b][/url]

[url=http://www.katespadeoutlets.us/][b]Kate Spade Outlet[/b][/url]

[url=http://www.uggbootsclearanceoutlet.us/][b]Ugg Boots Outlet[/b][/url]

[url=http://www.uggs-outletboots.us/][b]Uggs Outlet[/b][/url]

[url=http://www.timberland-outlet.us/][b]Timberland Outlet[/b][/url]

[url=http://www.ray-banoutlets.us/][b]Ray Ban Outlet[/b][/url]

[url=http://www.rayban-sunglasses.ca/][b]Ray Ban Sunglasses[/b][/url]

[url=http://www.adidas-nmd.org.uk/][b]Adidas NMD[/b][/url]

[url=http://www.timberlanduk.org.uk/][b]Timberland UK[/b][/url]

[url=http://www.ralphlaurens.org.uk/][b]Ralph Lauren[/b][/url]
Leave a Comment

Post Comment