Index: json.js --- json.js.orig 2006-06-29 08:25:57 +0200 +++ json.js 2006-06-29 08:36:15 +0200 @@ -4,22 +4,28 @@ This file adds these methods to JavaScript: + JSON.encode(object) object.toJSONString() This method produces a JSON text from an object. The object must not contain any cyclical references. + JSON.encode(array) array.toJSONString() This method produces a JSON text from an array. The array must not contain any cyclical references. + JSON.decode(string) string.parseJSON() This method parses a JSON text to produce an object or array. It will return false if there is an error. */ -(function () { + +var JSON = {}; + +JSON.encode = function (obj) { var m = { '\b': '\\b', '\t': '\\t', @@ -99,22 +105,28 @@ return '"' + x + '"'; } }; + return s.object(obj); +}; - Object.prototype.toJSONString = function () { - return s.object(this); - }; - - Array.prototype.toJSONString = function () { - return s.array(this); - }; -})(); - -String.prototype.parseJSON = function () { +JSON.decode = function (str) { try { return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test( - this.replace(/"(\\.|[^"\\])*"/g, ''))) && - eval('(' + this + ')'); + str.replace(/"(\\.|[^"\\])*"/g, ''))) && + eval('(' + str + ')'); } catch (e) { return false; } }; + +String.prototype.parseJSON = function () { + return JSON.decode(this); +}; + +Object.prototype.toJSONString = function () { + return JSON.encode(this); +}; + +Array.prototype.toJSONString = function () { + return JSON.encode(this); +}; +