Javascript PHP Serialize

Prototype implementation of PHP's Serialize function in Javascript. Handles most basic datatypes, and casts unknowns to strings. It can be tested from the console in your browser. Output can be verified against http://blog.tanist.co.uk/files/unserialize/.

Number.prototype.phpSerialize = function() { return 'd:' + this; } Boolean.prototype.phpSerialize= function() { return 'b:' + (this ? 1 : 0); } String.prototype.phpSerialize = function() { return 's:' + this.length + ':"' + this + '"'; } Array.prototype.phpSerialize = function() { result = 'a:' + this.length + ':{'; for (var i = 0; i < this.length; ++i) { result += 'i:' + i + ';'; var elem = this[i]; if (elem == null) { result += 'N;'; continue; } if (typeof elem.phpSerialize !== 'function') elem = elem.toString(); result += elem.phpSerialize(); if (elem instanceof Object || elem instanceof Array) continue; result += ';'; } result += '}'; return result; } Object.defineProperty(Object.prototype, 'phpSerialize', { value: function() { var i = 0, result = '', elem; for (prop in this) { ++ i; result += prop.phpSerialize() + ';'; elem = this[prop]; if (elem == null) { result += 'N;'; continue; } if (typeof elem.phpSerialize !== 'function') elem = elem.toString(); result += elem.phpSerialize(); if (elem instanceof Object || elem instanceof Array) continue; result += ';'; } result = 'a:' + i + ':{' + result + '}'; return result; }, enumerable: false });