Subversion Repositories cryptochat

Rev

View as "text/javascript" | Blame | Last modification | View Log | RSS feed

  1. //http://www.sitepoint.com/blogs/2009/08/19/javascript-json-serialization/
  2. //This might not produce as valid JSON as http://www.JSON.org/json2.js 2009-08-17
  3. var JSON = JSON || {};
  4.  
  5. // implement JSON.stringify serialization
  6. JSON.stringify = JSON.stringify || function (obj) {
  7.         var t = typeof (obj);
  8.         if(t == "undefined") {
  9.                 return;
  10.         } else if(typeof obj.toJSON != "undefined") {
  11.                 obj = obj.toJSON();
  12.                 if(typeof (obj) == "string")
  13.                         obj = '"'+obj.replace(/"/g, '\\"')+'"';
  14.                 return String(obj);
  15.         } else if (t != "object" || obj === null) {
  16.                 // simple data type
  17.                 if (t == "string")
  18.                         obj = '"'+obj.replace(/"/g, '\\"')+'"';
  19.                
  20.                 return String(obj);
  21.         } else {
  22.                 // recurse array or object
  23.                 var n, v, json = [], arr = (obj && obj.constructor == Array);
  24.                
  25.                 for (n in obj) {
  26.                         v = JSON.stringify(obj[n]);
  27.                         json[json.length] = (arr ? "" : '"' + n + '":') + String(v);
  28.                 }
  29.        
  30.                 return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
  31.         }
  32. };
  33.  
  34. if (typeof Date.prototype.toJSON == 'undefined') {
  35.         Date.prototype.toJSON = function (key) {
  36.                 return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null
  37.         };
  38.         String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) {
  39.                 return this.valueOf();
  40.         }
  41. }